116. Populating Next Right Pointers in Each Node

来源:互联网 发布:端口打开失败怎么回事 编辑:程序博客网 时间:2024/04/29 07:22

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然后设置一个next就行

代码如下(已通过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);
}
}
}
}

0 0
原创粉丝点击