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

[leetcode]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 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
拿到该题的第一反应是层次遍历,对每一层的节点进行链接,但是看到提示说需要常量空间。因此就尝试别的方法,已知,将亲兄弟节点进行链接是很容易的。每层的断裂带是堂兄弟,但是每一对堂兄弟的父节点都是亲兄弟,因此,可以得到这样的结论,根据断裂的堂兄弟的父节点(假设全部亲兄弟节点已经完成链接)可以将两个堂兄弟链接起来,比如说图中的5 、6是断裂的,但是我们可以在遍历到第二层时,可以根据2 3 提前(或滞后)将5 6 先关联起来。代码如下
	public void connect(TreeLinkNode root) {
		linkLeft2Right(root);
		TreeLinkNode left = root;
		while (left != null) {
			linkRight2left(left);
			left = left.left;
		}
	}

	private void linkLeft2Right(TreeLinkNode root) {
		if (root != null && root.left != null) {
			root.left.next = root.right;
		}else{
			return;
		}
		linkLeft2Right(root.left);
		linkLeft2Right(root.right);
	}

	private void linkRight2left(TreeLinkNode root) {
		TreeLinkNode node = root;
		while (node.next != null) {
			if(node.next.left !=null && node.right != null){ 
				node.right.next = node.next.left;
			}
			node = node.next;
		}
	}

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics