JZ57 二叉树的下一个结点

二叉树的下一个结点

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

解法一:中序遍历

通过next不断查找二叉树的根节点,然后再进行迭代or递归的中序遍历。当前一个节点为输入节点时,输出当前节点。
代码太傻,略。

解法二:左右孩子讨论+中序遍历子函数。

  1. 如果当前节点有右孩子,那么下一个结点显然为右孩子中序遍历的第一个元素。

  2. 如果当前节点没有左孩子,就要不断地向上追溯,直到当前节点不再是父节点的右孩子为止,然后输出父节点。

    public class Solution {
     public TreeLinkNode GetNext(TreeLinkNode pNode)
     {
         if(pNode.right!=null) { inorder(pNode.right); return ans;}
         while(pNode.next!=null&&pNode.next.right==pNode) pNode=pNode.next;
         return pNode.next;
     }
    
     TreeLinkNode ans=null;
    
     void inorder(TreeLinkNode pNode){
         if(pNode==null) return;
         inorder(pNode.left);
         if(ans==null) ans=pNode;
         inorder(pNode.right);
         return;
     }
    }

解法三:左右孩子讨论

基本思想和上面差不多,但是对于右孩子的情况,不需要写一个单独的子函数了。

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;
        }
        while(pNode.next!=null&&pNode.next.right==pNode)
            pNode=pNode.next;
        return pNode.next;
    }
}
全部评论

相关推荐

爱读书的放鸽子能手很...:刷个两端实习,冲春招,流水线什么时候不能去
我的秋招日记
点赞 评论 收藏
分享
迷茫的大四🐶:那你问他上班之后老实了没
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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