二叉树的下一个结点 --剑指offer

题目描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
 
思路一:先向上找到跟结点 然后中序遍历
public class Solution {
        boolean flag=false;
    TreeLinkNode result=null;
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        if(pNode == null) return null;
        TreeLinkNode head=pNode;
        while(head.next != null){
            head=head.next;
        }
        midOrder(head,pNode);
        return result;
    }

    private void midOrder(TreeLinkNode tree, TreeLinkNode pNode) {
        if(tree.left != null){
            midOrder(tree.left,pNode);
        }
        if(flag && result ==null) {//判断result==null非常重要 防止上层修改result的值
            result=tree;
            return ;
        }
        if(tree.val == pNode.val &&tree.left == pNode.left && tree.right==pNode.right && tree.next==pNode.next){
            flag=true;
        }
        if(tree.right != null){
            midOrder(tree.right,pNode);
        }
    }
}

思路二:

链接:https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e
来源:牛客网

可分成两大类:1、有右子树的,那么下个结点就是右子树最左边的点; 2、没有右子树的,也可以分成两类,a)是父节点左孩子(eg:N,I,L) ,那么父节点就是下一个节点 ; b)是父节点的右孩子(eg:H,J,K,M)找他的父节点的父节点的父节点...直到当前结点是其父节点的左孩子位置。如果没有eg:M,那么他就是尾节点。

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;
        }
        TreeLinkNode tem=pNode;
        while(pNode.next != null){
            pNode=pNode.next;
            if(pNode.left == tem){
                return pNode;
            }
            tem=pNode;
        }
        return  null;
    }

}
原文地址:https://www.cnblogs.com/nlw-blog/p/12466748.html