处理二叉树使得任何节点的右子树的最大值大于左子树的最大值

 

与二叉树的镜像很相似:https://blog.csdn.net/qq_35865125/article/details/79339200

思路:

遍历所有的节点,遍历到某个节点时,得到该节点的左子树的最大值Lmax,右子树的最大值Rmax,如果Lmax>Rmax,则交换左右子树。

可以写一个函数in getMaxVal(Node* root), 返回以root为根节点的树的最大值。 另外,可以考虑在Node结构体中增加变量记录其子树的最大值, 在遍历

节点时,采用深度优先的方法,先遍历最下层。

Code:

#pragma once
#include <iostream>
#include <stack>
#include <algorithm>

using namespace std;

class BiTreeHandle
{
public:
	struct Node {
		Node(int v = 0, Node* pL = nullptr, Node* pR = nullptr) :val(v), left(pL), right(pR)
		{
			bKnownMax = false;
		}
		int val;
		Node* left;
		Node* right;
		int maxVal;
		bool bKnownMax;
	};

	BiTreeHandle();
	~BiTreeHandle();

	//循环的方式遍历所有的节点,得到最大值
	int getMaxValofTree(Node* root) {
		if (!root)
			return INT_MIN;

		if (root->bKnownMax) { 
			return root->maxVal;
		}

		int resMax = root->val;
		stack<Node*> stackCach;
		stackCach.push(root);
		while (!stackCach.empty()){
			Node* temp = stackCach.top();
			stackCach.pop();
			//访问根节点
			if (temp->val > resMax) {
				resMax = temp->val;
			}

			if(temp->right)
				stackCach.push(temp->right);
			if (temp->left)
				stackCach.push(temp->left);
		}

		root->maxVal = resMax;
		root->bKnownMax = true;
		return resMax;
	}

    //递归的方式遍历所有的节点,得到最大值
	int getMaxValOfTreeRecus(Node* root) {
		if (root) {
			int rootVal = root->val;
			int leftMax = getMaxValOfTreeRecus(root->left);
			int rightMax = getMaxValOfTreeRecus(root->right);
			return std::max(rootVal, std::max(leftMax, rightMax));
		}
		return INT_MIN;
	}

	void solve(Node* root) {
		if (root) {
			solve(root->left);
			solve(root->right);

			if (root->left && root->right) {
				//bKnownMax信息并没有用上! 因为,solve函数采用的是深度优先递归,先判断底层节点。
				int leftMax = root->left->bKnownMax? root->left->maxVal: getMaxValofTree(root->left);
				int rightMax = root->right->bKnownMax ? root->right->maxVal : getMaxValofTree(root->right);
				if (leftMax > rightMax) {
					Node* temp = root->left;
					root->left = root->right;
					root->right = temp;
				}
			}

		}
	}

	void Test1() {
		Node* root = new Node(0);
		root->left = new Node(5);
		root->right = new Node(3);
		root->left->left = new Node(1);
		root->left->right = new Node(0);
		root->right->right = new Node(10);

		//int max = getMaxValofTree(root);
		//int max2 = getMaxValOfTreeRecus(root);
		solve(root);
		return;
	}
};

void main() {
	BiTreeHandle obj;
	obj.Test1();

	return;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值