Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all
next pointers are set to NULL.
For
example,
Given
the following perfect binary tree,
1 / 2 3 / \ / 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ 2 -> 3 -> NULL
/ \ / 4->5->6->7 -> NULL
1 public class Solution { 2 public void connect(TreeLinkNode root) { 3 if(root==null) return; 4 TreeLinkNode cur = root; 5 while(cur!=null){ 6 TreeLinkNode pre = cur; 7 while(pre!=null){ 8 if(pre.left!=null) 9 pre.left.next = pre.right; 10 if(pre.right!=null && pre.next!=null) 11 pre.right.next = pre.next.left; 12 pre = pre.next; 13 } 14 cur = cur.left; 15 } 16 } 17 }
Populating Next Right Pointers in Each Node
原文:http://www.cnblogs.com/krunning/p/3563993.html