【剑指Offer】二叉树的下一个结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27124771/article/details/84873708

题目描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

解题思路: 解题的时候要将情况考虑清楚,(1) 若一个结点有右子树,那么下一个结点就是右子树中的最左子结点。 (2) 若没有右子树,则向上遍历,找到第一个作为左子结点的结点。

public TreeLinkNode GetNext(TreeLinkNode pNode){
        
    if(pNode == null) return null;
        
    if(pNode.right != null){
        pNode = pNode.right;
        while(pNode.left != null){
            pNode = pNode.left;
        }
        return pNode;
    }
        
    while(pNode.next != null){
        if(pNode.next.left == pNode){
            return pNode.next;
        }   
        pNode = pNode.next;
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/qq_27124771/article/details/84873708
今日推荐