与二叉树的镜像很相似: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;
}