码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-03-02 01:07:13      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:lang   sim   while   weight   自己   end   class   mono   mon   

剑指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-8 二叉树的下一个节点

标签:lang   sim   while   weight   自己   end   class   mono   mon   

原文地址:https://www.cnblogs.com/muche-moqi/p/12393057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!