您的位置:首页 > Web前端 > Node.js

Leetcode Populating Next Right Pointers in Each Node II

2014-01-30 07:02 531 查看


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;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: