二叉树的下一个结点
http://blog.csdn.net/qq_27703417/article/details/70978102
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
- /*
- 注意这里的结点的定义比较特殊,不要惯性思维
- public class TreeLinkNode {
- int val;
- TreeLinkNode left = null;
- TreeLinkNode right = null;
- TreeLinkNode next = null;
- 千万注意:这里父节点用next而不是parent来表示
- TreeLinkNode(int val) {
- this.val = val;
- }
- }
- */
- //给出一个结点,找出这个结点在后序遍历中的下一个结点:分析可以,后继结点只可能来自3中情况
- public class Solution {
- public TreeLinkNode GetNext(TreeLinkNode pNode){
- if(pNode.right!=null){
- //情况1:有右子树,后继结点是右子树上的最左端结点
- TreeLinkNode temp=pNode.right;
- while(temp.left!=null){
- temp=temp.left;
- }
- return temp;
- }else if(pNode.next==null){
- //情况2:没有右子树且pNode没有父节点,则后继结点是null
- return null;
- }else if(pNode==pNode.next.left){
- //情况2:没有右子树且pNode有父节点且pNode是父节点的左结点,则后继结点就是父节点
- return pNode.next;
- }else{
- //情况3:没有右子树且pNode是父节点的右子树,则后继结点是向上作为左孩子的父节点
- TreeLinkNode temp=pNode;
- TreeLinkNode tempParent=pNode.next;
- while(tempParent!=null){
- if(temp==tempParent.left) return tempParent;
- temp=tempParent;
- tempParent=tempParent.next;
- }
- //执行到此还没有返回说明没有后继结点
- return null;
- }
- }
- }
posted on 2017-08-22 15:05 zhangxiaoyu 阅读(196) 评论(0) 收藏 举报
浙公网安备 33010602011771号