Populating Next Right Pointers in Each Node II 寻找右节点(重重重)

题目:

点击打开链接

解答:

方法与Populating Next Right Pointers in Each Node类似,需要从上至下,逐层寻找右节点。

对于一个根节点,我们这样求解:

他的左子树:

1  右子树存在,那么右节点就是右子树。

2  右子树不存在,首先寻找到父节点的右节点,如果父节点的右节点有子树,那么此左子树的右节点就是其子树,如果父节点的右节点没有子树,递归寻找父节点的右节点后面的右节点,直到有子树或者为空。

他的右子树:

1   寻找父节点右节点,做上述2步骤。


递归求该父节点的左右子树。

这里需要注意的是,需要先递归求解右子树,再求左子树,否则在上面的第二步过程中会出现父节点的右节点的右节点还未求解的情况。


图片示意一个节点的右子树是如何寻找其父节点的右节点的右节点的左子树为其有节点的。


代码:

#include <iostream>
#include<algorithm>
#include <cstdlib>
#include <vector>
#include <stack>	
#include <string>
#include <map>
#include <queue>
#include <unordered_set>
using namespace std;

 struct TreeLinkNode {
  int val;
  TreeLinkNode *left, *right, *next;
  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 };

 class Solution {
 public:
	 void connect(TreeLinkNode *root) {
		 if (root == NULL)
			 return;
		 //处理左子树
		 if (root->left)
		 {
			 //如果右子树存在,那么next就是右子树
			 if (root->right)
				 root->left->next = root->right;
			 //右子树不存在
			 else
			 {
				 TreeLinkNode *temp;
				 temp = root->next;
				 //递归寻找一个存在子节点的next节点,直到为空
				 while (1)
				 {
					 if (temp == NULL || temp->left || temp->right)
						 break;
					 temp = temp->next;
				 }
				 //如果不是空节点
				 if (temp)
				 {
					 //节点的左子树存在
					 if (temp->left)
						 root->left->next = temp->left;
					 //节点的右子树存在
					 else if (temp->right)
						 root->left->next = temp->right;
				 }
			 }
		 }
		 if (root->right)
		 {
			 TreeLinkNode *temp;
			 temp = root->next;
			 //递归寻找一个存在子节点的next节点,直到为空
			 while (1)
			 {
				 if (temp == NULL || temp->left || temp->right)
					 break;
				 temp = temp->next;
			 }
			 //如果不是空节点
			 if (temp)
			 {
				 //节点的左子树存在
				 if (temp->left)
					 root->right->next = temp->left;
				 //节点的右子树存在
				 else if (temp->right)
					 root->right->next = temp->right;
			 }
		 }
		 connect(root->right);
		 connect(root->left);
	 }
 };

int main()
{
	Solution sl;

	TreeLinkNode *root = new TreeLinkNode(2);
	root->left = new TreeLinkNode(1);
	root->right = new TreeLinkNode(3);
	
	root->left->left = new TreeLinkNode(0);
	root->left->right = new TreeLinkNode(7);
	root->left->right->left = new TreeLinkNode(1);
	root->left->right->right = new TreeLinkNode(0);
	root->left->right->right->left = new TreeLinkNode(7);

	root->right->left = new TreeLinkNode(9);
	root->right->right = new TreeLinkNode(1);
	root->right->right->left = new TreeLinkNode(8);
	root->right->right->right = new TreeLinkNode(8);

	sl.connect(root);

	cout << "-------";
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值