Leetcode Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

 Total Accepted: 6129 Total Submissions: 17922My Submissions

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

直接上递归法

void connect(TreeLinkNode *root) 
	{
		if (!root || !root->left) return;
		root->left->next = root->right;
		con(root->left, root->right);
	}
	void con(TreeLinkNode *lTree, TreeLinkNode *rTree)
	{
		if (lTree->left) lTree->left->next = lTree->right;
		if (rTree->left) rTree->left->next = rTree->right;
		else return;
		lTree->right->next = rTree->left;
		con(lTree->left, lTree->right);
		con(lTree->right, rTree->left);
		con(rTree->left, rTree->right);
	}


下面参考leetcode论坛上的程序写了个程序

//新知识点:
//重点注意:利用新构造的数据结构
void connect(TreeLinkNode* root) 
{
	if (!root || !root->left || !root->right)
		return;
	TreeLinkNode* rightSibling;
	TreeLinkNode* p1 = root;
	while (p1) 
	{
		rightSibling = p1->next? p1->next->left:NULL;
		p1->left->next = p1->right;
		p1->right->next = rightSibling;
		p1 = p1->next;
	}
	connect(root->left);
}

有人会觉得使用递归并不符合常数空间的题意,那么可以改成非递归:

void connect(TreeLinkNode *root) 
	{
		TreeLinkNode *nextLev = root? root->left:NULL;
		while (nextLev)
		{
			for ( ; root; root = root->next) 
			{
				TreeLinkNode *rightSibling = root->next? root->next->left:NULL;
				root->left->next = root->right;
				root->right->next = rightSibling;
			}
			root = nextLev;
			nextLev = nextLev->left;
		}
	}



Leetcode Populating Next Right Pointers in Each Node

上一篇:exchange 用户建立好之后,无法自动产生邮箱 问题解决


下一篇:使用sessionStorage、localStorage存储数组与对象