Sword refers to offer acwing 19 The next node of the binary tree (find successor)

Topic

Insert picture description here

answer

  1. The successor of a node in the binary tree: the successor is strictly greater than the minimum value
    Insert picture description here
    of this node . In-order traversal: ACBDFHEMG In fact, in the order of in-order traversal, the next node of each node is its successor node, and the previous node is its predecessor node.
  1. If the current node has a right son, then the leftmost node in the right subtree is the successor of the current node. For example, the successor of F is H
  1. If the current node does not have a right son, you need to look up along the father and find the first node that is the left son of father. The father of this node is the successor of the current node. For example, if the current node is D, the first satisfaction is that the node of the left son of father is F, then the father of C is the successor of D, that is, F is the successor of D.
  1. Time complexity, because whether it is looking up or down, it is only the height of the tree that is traversed at most, so it is O(h), and h is the height of the tree

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode *father;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL), father(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* inorderSuccessor(TreeNode* p) {
    
    
        
        if (!p) return NULL;

        if (p->right) {
    
      //如果存在右子树
            p = p->right;
            while (p->left) p = p->left;
            return p;
        } else {
    
    
            while (p->father && p->father->right==p){
    
    
                p=p->father;
            }
            if(p->father) return p->father;
            return NULL;
        }
        
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114887878