剑指57.二叉树的下一个节点

题目描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
 

思路

画图,分情况讨论。

1)如果一个节点 有 右子树,打印右子树最左边的节点。

2)一个节点 没有 右子树, 并且它还是它父节点的左孩子,直接打印它的父节点。

3)一个节点 没有 右子树,并且它还是它父节点的右孩子,那么一直向上找,直到上级是上上级的左孩子。如果存在,打印这个节点的父节点。

 

解法

/*
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;
        // 1.有右子树
        if (pNode.right != null){
            pNode = pNode.right;
            while (pNode.left != null){
                pNode = pNode.left;
            }
            return pNode;
        }else{
            // 2.没有右子树,并且是左孩子,那么直接返回它的父节点
            if (pNode.next != null && pNode.next.left == pNode){ // 细节,必须先判断一下是否有父节点
                return pNode.next;
            }
            // 3.没有右子树,并且是右孩子
            if (pNode.next != null && pNode.next.right == pNode){
                while (pNode.next != null && pNode.next.left != pNode){
                    pNode = pNode.next;
                }
                return pNode.next;
            }
        }
        return null;
    }
}

 

 

posted @ 2020-09-06 15:49  不学无墅_NKer  阅读(89)  评论(0编辑  收藏  举报