其他分享
首页 > 其他分享> > 剑指offer-8 二叉树的下一个节点

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

作者:互联网

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

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

思路:

  1. 右侧有节点,直接打印
  2. 右侧没节点
    1. 此节点的父节点的左节点是自己,打印
    2. 此节点的父节点的右节点是自己,向上继续找,直到满足2.1

自己解答:

/*
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;
        TreeLinkNode next = null;
        if(pNode.right != null){
            TreeLinkNode pRight = pNode.right;            
            while(pRight.left != null)
                pRight = pRight.left;
            next = pRight;
        }else if(pNode.next != null){
            TreeLinkNode curNode = pNode;
            TreeLinkNode pParrent = pNode.next;
            while(pParrent != null && pParrent.right == curNode){
                curNode = pParrent;
                pParrent = pParrent.next;
            }
            next = pParrent;
        }
        return next;        
    }
}

犯的错误:

注意:

别人解答:

标签:offer,pParrent,next,TreeLinkNode,pNode,二叉树,null,节点
来源: https://www.cnblogs.com/muche-moqi/p/12393057.html