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:
- 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
思路:就是一个BFS,把每一层的节点向右链接一下
代码如下(已通过leetcode)
public class Solution {
public void connect(TreeLinkNode root) {
List<TreeLinkNode> list=new ArrayList<TreeLinkNode>();
if(root==null) return;
Queue que=new LinkedList<>();
que.add(root);
BFS(list,que);
List<List<TreeLinkNode>> lists=new ArrayList<List<TreeLinkNode>>();
int count=0;
int i=0;
while(count<list.size()) {
List<TreeLinkNode> temp=list.subList((int)Math.pow(2, i)-1,(int)Math.pow(2, i+1)-1);
lists.add(temp);
count+=(int)Math.pow(2, i);
i++;
}
for(int j=0;j<lists.size();j++) {
int k=0;
while(k<lists.get(j).size()-1) {
lists.get(j).get(k).next=lists.get(j).get(k+1);
k++;
}
}
}
private void BFS(List<TreeLinkNode> list,Queue que) {
// TODO Auto-generated method stub
TreeLinkNode temp;
while(!que.isEmpty()) {
temp=(TreeLinkNode) que.remove();
list.add(temp);
if(temp.left!=null) {
que.add(temp.left);
que.add(temp.right);
}
}
}
}