首页 > 其他 > 详细

55、二叉树的下一个结点

时间:2017-08-31 20:52:00      阅读:218      评论:0      收藏:0      [点我收藏+]

一、题目

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

二、解法

 1 /*
 2 public class TreeLinkNode {
 3     int val;
 4     TreeLinkNode left = null;
 5     TreeLinkNode right = null;
 6     TreeLinkNode next = null;
 7 
 8     TreeLinkNode(int val) {
 9         this.val = val;
10     }
11 }
12 */
13 public class Solution {
14    public TreeLinkNode GetNext(TreeLinkNode pNode)
15     {
16         if(pNode == null)
17             return null;
18         if(pNode.right != null){//如果有右子树,则找右子树的最左节点
19             pNode = pNode.right;
20             while(pNode.left != null)
21                 pNode = pNode.left;
22             return pNode;
23         }
24         while(pNode.next != null){//没右子树,则找第一个当前节点是父节点左孩子的节点
25             if(pNode.next.left == pNode)
26                 return pNode.next;
27             pNode = pNode.next;
28         }
29         return null;//退到了根结点仍没找到,则返回null
30    }
31 }

 

55、二叉树的下一个结点

原文:http://www.cnblogs.com/fankongkong/p/7460253.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!