Programmer interview golden classic-interview questions 04.06. Successor

1. Topic introduction

Design an algorithm to find the "next" node (that is, the in-order successor) of the specified node in the binary search tree.

If the specified node has no corresponding "next" node, null is returned.

Example 1:

Input: root = [2,1,3], p = 1

  2
 / \
1   3

Output: 2
Example 2:

Input: root = [5,3,6,2,4,null,null,1], p = 6

      5
     / \
    3   6
   / \
  2   4
 /   
1

Output: null

Source: LeetCode
Link: https://leetcode-cn.com/problems/successor-lcci The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       This question examines the middle-order traversal of the binary tree, and finds the next node of the specified node in the middle-order traversal.

Three, problem-solving code

class Solution {
public:
    //二叉树的中序遍历
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        stack<TreeNode*> st;
        TreeNode* preNode = NULL;
        while(!st.empty() || root)
        {
            while(root)
            {
                st.push(root);
                root = root->left;
            }
            root = st.top();
            st.pop();
            if(p == preNode)
                return root;
            preNode = root;
            root = root->right;
        }
        return NULL;
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108056899