`
huntfor
  • 浏览: 195480 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Populating Next Right Pointers in Each Node II

 
阅读更多

新博文地址:[leetcode]Populating Next Right Pointers in Each Node II 

Populating Next Right Pointers in Each Node 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:

You may only use constant extra space.
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

 貌似leetcode特别喜欢考察树的BFS(二叉树或者普通的树),这个不多说了,对每一层分别处理就好

	public void connect(TreeLinkNode root){
		if(root == null || (root.left == null && root.right == null)){
			return ;			
		}
		ArrayDeque<TreeLinkNode> pre = new ArrayDeque<TreeLinkNode>();
		ArrayDeque<TreeLinkNode> post = new ArrayDeque<TreeLinkNode>();
		pre.offer(root);
		while(!pre.isEmpty()){
			TreeLinkNode tem = pre.poll();
			if(tem.left != null){
				TreeLinkNode left = tem.left;
				post.offer(left);
			}
			if(tem.right != null){
				TreeLinkNode right = tem.right;
				post.offer(right);
			}
			if(pre.isEmpty()){
				if(post.isEmpty()){
					return;
				}
				linkNodeOfQueue(post);
				pre = post.clone();
				post.clear();
			}
		}
	}
	
	private void linkNodeOfQueue(ArrayDeque<TreeLinkNode> link){
		if(link == null || link.size() == 1){
			return ;
		}
		TreeLinkNode pre = link.peek();
		for(TreeLinkNode post : link){
			if(post == pre){
				continue;
			}
			pre.next = post;
			pre = post;
		}
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics