我觉得这两道题没有技巧可言,唯有把逻辑弄清楚,再用代码把自己的逻辑写下来。
下面是这两道题的AC代码:
1 /** 2 * Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 3 * @param root 4 */ 5 public void connect(TreeLinkNode root){ 6 if(root == null) 7 return; 8 root.next = null; 9 if(root.left == null && root.right == null) 10 return; 11 TreeLinkNode next = root; 12 while(next.left!=null && next.right!=null){ 13 TreeLinkNode temp = next.left; 14 while(true) 15 { 16 if(next.left!=null&& next.right!=null) 17 { 18 next.left.next = next.right; 19 next.right.next = next.next==null?null:next.next.left; 20 } 21 if(next.next == null) 22 break; 23 next = next.next; 24 } 25 next = temp; 26 } 27 } 28 /** 29 * What if the given tree could be any binary tree? Would your previous solution still work? 30 * @param root 31 */ 32 public void connectAny(TreeLinkNode root){ 33 if(root == null) 34 return ; 35 //the root next pointer point to null; 36 root.next = null; 37 if(root.left == null && root.right == null) 38 return ; 39 //the current node to be handled 40 TreeLinkNode curr = root; 41 42 while(curr!=null){ 43 TreeLinkNode next =null; 44 TreeLinkNode temp = null; 45 while(true){ 46 //find the non-leaf node 47 while(curr.left == null && curr.right == null){ 48 if(curr.next == null) 49 break; 50 curr = curr.next; 51 } 52 if(next == null) 53 next = curr.left==null?(curr.right==null?null:curr.right):curr.left; 54 //temp the node who need to populate the next pointer 55 if(temp !=null) 56 temp.next = curr.left==null?(curr.right==null?null:curr.right):curr.left; 57 // 58 if(curr.left!=null && curr.right!=null) 59 { 60 curr.left.next = curr.right; 61 temp = curr.right; 62 }else if(curr.left!=null){ 63 temp = curr.left; 64 }else if(curr.right!=null){ 65 temp = curr.right; 66 } 67 68 if(curr.next ==null){ 69 if(temp!=null) 70 temp.next = null; 71 break; 72 } 73 curr = curr.next; 74 } 75 curr = next; 76 } 77 }