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


如何处理各个细节的问题很重要,决定了能否写出更加简洁的程序来。

void connect(TreeLinkNode *root) 
	{
		while (root && !root->left && !root->right) root = root->next;
		if (root == NULL) return;
		
		TreeLinkNode *rightSibling;
		TreeLinkNode *p1 = root;
		while (p1) 
		{
			TreeLinkNode *p_next = p1->next;
			while (p_next && !p_next->left && !p_next->right) 
				p_next = p_next->next;

			if (p_next)
				rightSibling = p_next->left? p_next->left:p_next->right;
			else rightSibling = NULL;

			if (p1->left && p1->right)
			{
				p1->left->next = p1->right;
				p1->right->next = rightSibling;
			}
			else if (p1->right)
			{
				p1->right->next = rightSibling;
			}
			else
			{
				p1->left->next = rightSibling;
			}

			p1 = p_next;
		}
		if (root->left)
			connect(root->left);
		else if(root->right)
			connect(root->right);
	}

Leetcode论坛上的一个简洁的程序,写得太好了,编程功底就在微小的差别中体现出来了。

具体思想是和我上面的程序一样的。

//LeetCode论坛上的
	// the link of level(i) is the queue of level(i+1)
	void connect2(TreeLinkNode * n) {
		while (n) {
			TreeLinkNode * next = NULL; // the first node of next level
			TreeLinkNode * prev = NULL; // previous node on the same level
			for (; n; n=n->next) {
				if (!next) next = n->left?n->left:n->right;

				if (n->left) {
					if (prev) prev->next = n->left;
					prev = n->left;
				}
				if (n->right) {
					if (prev) prev->next = n->right;
					prev = n->right;
				}
			}
			n = next; // turn to next level
		}
	}


//2014-2-17 update
	void connect(TreeLinkNode *root) 
	{
		while (root)
		{
			TreeLinkNode *next = NULL;
			TreeLinkNode *pre = NULL;
			for ( ; root; root = root->next)
			{
				helper(root->left, next, pre);
				helper(root->right, next, pre);
			}
			root = next;
		}
	}
	void helper(TreeLinkNode *&node, TreeLinkNode *&n, TreeLinkNode *&p)
	{
		if (!node) return;
		if (!n) n = node;
		if (p) p->next = node;
		p = node;
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值