标签:
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 to NULL
.
Initially, all next pointers are set to NULL
.
Note:
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
思路: 需要一个node记录每一层最左侧的起始点,还需要一个cur指针在每一层从左向右移动串联起next指针
1 public void connect(TreeLinkNode root) { 2 if (root == null) { 3 return; 4 } 5 TreeLinkNode leftHead = root; 6 while (leftHead != null && leftHead.left != null) { 7 TreeLinkNode cur = leftHead; 8 while (cur != null) { 9 cur.left.next = cur.right; 10 cur.right.next = cur.next == null ? null : cur.next.left; 11 cur = cur.next; 12 } 13 leftHead = leftHead.left; 14 } 15 }
II:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
For example,
Given the following binary tree,
1 / 2 3 / \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ 4-> 5 -> 7 -> NULL
思路:基本的思路都是一样的。但是因为这个不是个perfect binary tree. 所以在串联next指针时,就得想办法记录当前点得前一个点,我们引入pre指针。
并且,每一层的起始点也不一定是该层最左侧的位置。所以用dummy node记录起点。
1 public void connect(TreeLinkNode root) { 2 if (root == null) { 3 return; 4 } 5 TreeLinkNode leftNode = root; 6 while (leftNode != null) { 7 TreeLinkNode dummy = new TreeLinkNode(0); 8 TreeLinkNode pre = dummy; 9 TreeLinkNode cur = leftNode; 10 while (cur != null) { 11 if (cur.left != null) { 12 pre.next = cur.left; 13 pre = pre.next; 14 } 15 if (cur.right != null) { 16 pre.next = cur.right; 17 pre = pre.next; 18 } 19 cur = cur.next; 20 } 21 leftNode = dummy.next; 22 } 23 }
Populating Next Right Pointers in Each Node I && II
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4669179.html