Populating Next Right Pointers in Each Node
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
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
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
solution:
这其实就是个BFS,使用一个队列既可,为了方便,在每一层扩展完之后向队列中加入一个null。在对next point 赋值时,如果发现下一项是null,则直接给next = null.
由于只能使用constant 空间,所以不能这么做,由于是一棵树,所以考虑递归。
1 /** 2 * Definition for binary tree with next pointer. 3 * public class TreeLinkNode { 4 * int val; 5 * TreeLinkNode left, right, next; 6 * TreeLinkNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public void connect(TreeLinkNode root) { 11 // Start typing your Java solution below 12 // DO NOT write main() function 13 if(root == null) return; 14 if(root.left != null){ 15 root.left.next = root.right; 16 } 17 if(root.right != null){ 18 root.right.next = ((root.next != null)? root.next.left : null); 19 } 20 connect(root.left); 21 connect(root.right); 22 } 23 }
posted on 2013-09-11 07:45 Step-BY-Step 阅读(207) 评论(0) 编辑 收藏 举报