找二叉树中指定节点在中序遍历中的下一个节点

来源:互联网 发布:别墅 网络 编辑:程序博客网 时间:2024/06/07 18:51
class Solution {
 class TreeLinkNode {    int val;    TreeLinkNode left = null;    TreeLinkNode right = null;    TreeLinkNode next = null;
    TreeLinkNode(int val) {        this.val = val;    }}    public TreeLinkNode GetNext(TreeLinkNode pNode)    {        if(pNode==null)        return null;        TreeLinkNode right = pNode.right;//右子树        TreeLinkNode result = null;        //节点有右子树,则为右子树总最左边的节点        if(right!=null){        while(right.left!=null)        right = right.left;        result = right;        }else{//没有右子树        TreeLinkNode f = pNode.next;//父节点        if(f==null);//根节点        if(f!=null){//存在父节点        TreeLinkNode fLeft = f.left;        if(fLeft==pNode){//在左子树上           result= f;        }else{//在右子树上        //找到根节点        TreeLinkNode root=f.next;        while(root.next!=null){        f = f.next;        root=f.next;        }        TreeLinkNode rootleft = root.left;        if(f==rootleft)        result = root;               }                }        }        return result;     }}


0 0
原创粉丝点击