1. 程式人生 > >57二叉樹的下一個結點

57二叉樹的下一個結點

return 一個 color 遍歷 思路 找到 == lin 結點

題目描述

給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。註意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指針。



思路:
如果一個節點有右子樹,那麽他的下一個節點就是它的右子樹中的最左節點。
如果一個節點沒有右子樹,如果節點是它父節點的左子節點,那麽它的下一個節點就是它的父節點。
如果一個節點即沒有右子樹,並且它還是它父節點的右子節點,我們可以沿著指向父節點的指針一直向上遍歷,直到找到一個是他父節點的左子節點的節點。

 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 node){ 15 if(node == null) return null; 16 if(node.right!=null
){ //1、右節點不為空 17 //node 的下一個節點就是 當前node的右子樹中,最左的節點 18 node = node.right; 19 while(node.left!=null) 20 node = node.left; 21 return node; 22 } 23 else if(node.next!=null){//2右節點為空,分2種情況 24 //2.1、node是父節點的左子節點,那麽node的下一個節點就是它的父親節點。
25 if(node.next.left==node) return node.next; 26 //2.2、node 即沒有右子樹,並且是父節點的右子節點,沿著指針一直往上遍歷, 27 //直到找到一個是他父節點的左子節點的節點。 28 if(node.next.right==node){ 29 while(node.next!=null){ 30 if(node.next.left==node) return node.next; 31 node = node.next; 32 } 33 } 34 } 35 return null; 36 } 37 }

57二叉樹的下一個結點