AcWing 19. The next node of the binary tree (the nature of the in-order sequence of the binary tree)

Title:

给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。

注意:
如果给定的节点是中序遍历序列的最后一个,则返回空节点;
二叉树一定不为空,且给定的节点一定不是空节点;

solution:

中序遍历:->->1.如果当前节点存在右儿子,那么右子树中左下角的节点就是答案.

2.如果当前节点不存在有儿子,那么说明当前节点是"左->根->右"中的右,
此时需要向上找到一个祖先,满足当前节点在这个祖先的左子树中,
因为当前节点是这个祖先的左子树的右下角,
这道这样的祖先后,这个祖先就是答案.

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->right){
    
    
            p=p->right;
            while(p->left){
    
    
                p=p->left;
            }
            return p;
        }else{
    
    
            while(p->father&&p==p->father->right){
    
    
                p = p->father;
            }
            return p->father;
        }
    }
};

Guess you like

Origin blog.csdn.net/weixin_44178736/article/details/115027016