class Solution {
public:
TreeNode* construct(vector<int>& nums){
TreeNode* root = new TreeNode(0);
if (nums.size()==1){//处理叶子结点
root->val = nums[0];
return root;
}
//查找根节点(最大值)
int maxValue=0;
int maxIndex=0;
for (int i=0; i<nums.size(); i++){
if (maxValue < nums[i]){
maxValue = nums[i];
maxIndex = i;
}
}
root->val = maxValue;
//切分左右子树
if (maxIndex>0){ //说明左子树不为空
vector<int> leftTree(nums.begin(), nums.begin()+maxIndex);
root->left = construct(leftTree);
}
if (maxIndex < nums.size()-1){
vector<int> rightTree(nums.begin() + maxIndex+1, nums.end());
root->right = construct(rightTree);
}
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums);
}
};
思路:返回值和形参:构造好的二叉树的根节点和数组
终止条件:使用前序遍历完成对整个树的构造或者当前节点为叶子结点时返回root。
处理过程:前序遍历。
坑:必须这样初始化TreeNode* root = new TreeNode(0);
TreeNode* root;这样直接定义会报错SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:38:15。
617.合并二叉树
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1==nullptr) return root2;
if (root2==nullptr) return root1;
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
相信自己就行了
700.二叉搜索树中的搜索
//递归
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root==nullptr || root->val == val) return root;//当前节点为空或者为目标节点,就返回当前节点
TreeNode* result = new TreeNode(0);
if (root->val > val){ //当前节点大了,就往左子树找
result = searchBST(root->left, val);
}
if (root->val < val){
result = searchBST(root->right, val);
}
return result;
}
};
// 迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root!=nullptr){
if (root->val>val) root=root->left;
else if (root->val<val) root=root->right;
else{
return root;
}
}
return nullptr; //没找到
}
};
98.验证二叉搜索树
//使用数组判断,中序遍历是有序的,将二叉树中序遍历的结果保存在一个数组中,判断这个数组是否有序
class Solution {
public:
vector<int> tree;
bool isValidBST(TreeNode* root) {
if (root==nullptr) return false; //空节点就不会在进行下列处理了
isValidBST(root->left);
tree.push_back(root->val);
isValidBST(root->right);
for (int i=0; i<tree.size()-1; i++){
if (tree[i]>=tree[i+1])
return false;
}
return true;
}
};
// 使用maxValue进行比较,还是中序遍历
class Solution {
public:
long long maxValue = LONG_MIN;
bool isValidBST(TreeNode* root) {
if (root==nullptr) return true;
bool leftResult = isValidBST(root->left);
if (root->val > maxValue){
maxValue = root->val;
}
else{
return false;
}
bool rightResult = isValidBST(root->right);
return leftResult&&rightResult; //收集每一层的结果,如果有false就层层上传
}
};
返回值没必要的话可以不接住。