二叉树的下一个节点,各种情况判断法

二叉树的下一个结点

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

public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        //叶子节点
        if(pNode.left == null && pNode.right == null){

            //父节点为空吗?
            if(pNode.next == null){
                return null;

            //父节点不空,判断自己是父节点的左子节点还是右子节点

                //左子节点,输出父节点
            }else if(pNode.next.left == pNode){
                return pNode.next;
                //右子节点,
            }else if(pNode.next.right == pNode){
                //如果有父的父节点的左节点为当前的父节点,则输出(先判空)
                if(pNode.next.next != null && pNode.next.next.left == pNode.next){
                    return pNode.next.next;
                //中序遍历,左根右 走,不可能往左走
                }else if(pNode.next.next.right == pNode.next){
                    return null;
                }    
            }
        }else{ 
            //非叶子节点

            //如果右子节点空,只能往上一层走看看能不能输出
            if(pNode.right == null){
                //如果父不空,且父的左=当前节点,输出为父节点
                if(pNode.next != null && pNode.next.left == pNode){
                    return pNode.next;
                //否则空
                }else{
                    return null;
                }
            //右子节点不空,则需要持续遍历到右子节点的最左节点输出即可
            }else{
                TreeLinkNode temp = pNode.right;
                while(temp.left != null){
                    temp = temp.left;
                }
                return temp;
            }
        }
        return null;
    }
}
全部评论

相关推荐

飞屋一号:实话实说就行,先争取一下能不能线上,不行就直接放弃,付出与回报不成正比
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务