[Sword refers to offer punch card] 19. The next node of the binary tree

19. Next Node in Binary Tree

The main idea is divided into two steps:

  1. If there is a right subtree, the leftmost of the right subtree
  2. If there is no right subtree, it keeps looking for the parent node until the current node is not the right subtree of the parent node.
/**
 * 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->right) {
    
    
            p = p->right;
            while (p->left) p = p->left;
            return p;
        }
        
        while (p->father && p == p->father->right) p = p->father;
        return p->father;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326067163&siteId=291194637