200130题(递归(自上而下递归,比较简单))

在这里插入图片描述
核心:自上而下

class Node {
public:
	int val;
	Node* left;
	Node* right;
	Node* next;

	Node() : val(0), left(NULL), right(NULL), next(NULL) {}

	Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

	Node(int _val, Node* _left, Node* _right, Node* _next)
		: val(_val), left(_left), right(_right), next(_next) {}
};
//每次先将 root的左结点->next = root右结点, root右结点->next = root->next的左结点
class Solution {
public:
	Node* connect(Node* root) {//自上而下
		if (root == NULL || root->left == NULL)
			return root;
		//根据题意,root如果有左结点就必有右结点
		root->left->next = root->right;
		if (root->next != NULL)root->right->next = root->next->left;
		connect(root->left);
		connect(root->right);
		return root;
	}

};

在这里插入图片描述
对于任意一次递归,只考虑如何设置子结点的 next 属性, 分为三种情况:
没有子结点:直接返回
有一个子结点:将这个子结点的 next 属性设置为同层的下一个结点,即为 root->next 的最左边的一个子结点,如果 root->next 没有子结点,则考虑 root->next->next,依次类推
有两个结点:左子结点指向右子结点,然后右子结点同第二种情况的做法
注意递归的顺序需要从右到左

class Solution {
public:
	Node* connect(Node* root) {
		if (root == NULL)
			return NULL;
		if (root->left != NULL || root->right != NULL)
		{
			if (root->left != NULL&&root->right != NULL)
				root->left->next = root->right;

			Node*child_layer = root->right ? root->right : root->left;
			Node*father_layer = root->next;

			while (father_layer != NULL&&father_layer->left == NULL&&father_layer->right == NULL)
			{
				father_layer = father_layer->next;
			}
			if (father_layer == NULL)
				child_layer->next = NULL;
			else
				child_layer->next = father_layer->left ? father_layer->left : father_layer->right;

			connect(root->right);
			connect(root->left);


		}
		return root;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值