剑指offer P65 二叉树的下一个节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AK_97_CT/article/details/86937968
/**
 * 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) {
        //一、p有右子树,那么p的后继节点就是p的右子树的最左节点
        //二、p没有右子树,这又分两种情况
        //1、p是父节点的左子树,那么p的父节点就是p的后继节点
        //2、p是父节点的右子树,从p往上找父节点,知道某个节点是父节点的左子树,这时这个节点的父节点就是p的后继节点
        if(p==nullptr) return nullptr;
        if(p->right)
        {
            TreeNode* pright=p->right;
            while(pright->left) pright=pright->left;
            return pright;
        }
        else{
            while(p->father&&p==p->father->right) p=p->father;
            return p->father;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/AK_97_CT/article/details/86937968