二叉树的下一节点

二叉树的下一个结点

http://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e

分情况:

  • 当前节点有右子树,那下一节点肯定是右子树的最左节点
  • 当前节点没有右子树
    • 当前节点是父节点的左节点,下一个是父节点
    • 当前节点是父节点的右节点,下一个是顺着父节点遍历上去的父节点
/*
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){
            pNode = pNode.right;
            while(pNode.left != null)
                pNode = pNode.left;
            return pNode;
        }else{    //当前节点没有右子树
            while(pNode.next != null){
                if(pNode.next.left == pNode){    //当前节点是父节点的左子树
                    return pNode.next;
                }else{    //当前节点是父节点的右子树
                    pNode = pNode.next;
                }
            }

        }
        return null;
    }
}
全部评论

相关推荐

勤劳的鲸鱼在okr拆解:没有别的选择就去吧,有实习和没实习找工作是天上地下
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务