剑指Offer 8:二叉树的下一个结点

/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        //异常判断
        if(pNode == null){
            return null;
        }
        //若右子树不为空,则下一个节点是右子树的最左子树节点
        if(pNode.right!=null){
            TreeLinkNode tmp = pNode.right;
            while(tmp.left!=null){
                tmp = tmp.left;
            }
            return tmp;
        }
        
        //若左子树为空,则依次向上遍历其父节点,直到某个节点是其父节点的左子树
        TreeLinkNode tmp = pNode;
        while(tmp.next!=null){
            if(tmp.next.left==tmp){
                return tmp.next;
            }
            tmp = tmp.next;
            
        }
        return null;   
    }
}

 

posted @ 2020-10-22 15:37  dlooooo  阅读(73)  评论(0编辑  收藏  举报