二叉树的下一个结点

http://blog.csdn.net/qq_27703417/article/details/70978102

 

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

 

  1. /* 
  2. 注意这里的结点的定义比较特殊,不要惯性思维 
  3. public class TreeLinkNode { 
  4.     int val; 
  5.     TreeLinkNode left = null; 
  6.     TreeLinkNode right = null; 
  7.     TreeLinkNode next = null; 
  8.     千万注意:这里父节点用next而不是parent来表示 
  9.     TreeLinkNode(int val) { 
  10.         this.val = val; 
  11.     } 
  12. */  
  13. //给出一个结点,找出这个结点在后序遍历中的下一个结点:分析可以,后继结点只可能来自3中情况  
  14. public class Solution {  
  15.     public TreeLinkNode GetNext(TreeLinkNode pNode){  
  16.         if(pNode.right!=null){  
  17.             //情况1:有右子树,后继结点是右子树上的最左端结点  
  18.             TreeLinkNode temp=pNode.right;  
  19.             while(temp.left!=null){  
  20.                 temp=temp.left;  
  21.             }  
  22.             return temp;  
  23.         }else if(pNode.next==null){  
  24.             //情况2:没有右子树且pNode没有父节点,则后继结点是null  
  25.             return null;  
  26.         }else if(pNode==pNode.next.left){  
  27.            //情况2:没有右子树且pNode有父节点且pNode是父节点的左结点,则后继结点就是父节点  
  28.             return pNode.next;  
  29.         }else{  
  30.             //情况3:没有右子树且pNode是父节点的右子树,则后继结点是向上作为左孩子的父节点  
  31.             TreeLinkNode temp=pNode;  
  32.             TreeLinkNode tempParent=pNode.next;  
  33.             while(tempParent!=null){  
  34.                 if(temp==tempParent.left) return tempParent;  
  35.                 temp=tempParent;  
  36.                 tempParent=tempParent.next;  
  37.             }  
  38.             //执行到此还没有返回说明没有后继结点  
  39.             return null;  
  40.         }  
  41.     }  
  42. }  

posted on 2017-08-22 15:05  zhangxiaoyu  阅读(196)  评论(0)    收藏  举报

导航