Day20——二叉树Ⅵ
目标:
● 654.最大二叉树
● 617.合并二叉树
● 700.二叉搜索树中的搜索
● 98.验证二叉搜索树
654.最大二叉树
思路:
1. 找到最大值
2. 若数组元素为1,返回,否则继续
3. 构建左子树数组
4. 构建右子树数组
TreeNode* recursion(vector<int>& nums) {
int rootIndex = -1;
int size = nums.size();
int maxNum = INT_MIN;
for(int i = 0; i < size; i++) {
if(maxNum < nums[i]) {
maxNum = nums[i];
rootIndex = i;
}
}
TreeNode* root = new TreeNode(maxNum);
if(size == 1) return root;
// 左闭右开
vector<int> leftNums(nums.begin(), nums.begin() + rootIndex);
vector<int> rightNums(nums.begin() + rootIndex + 1, nums.end());
if(leftNums.size() > 0) root->left = recursion(leftNums);
if(rightNums.size() > 0) root->right = recursion(rightNums);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return recursion(nums);
}
617.合并二叉树
思路:两节点重叠
- 若其中一个节点为空,返回另一节点
- 若两个都不为空,构造节点
TreeNode* recursion(TreeNode* root1, TreeNode* root2, TreeNode* root) {
if(root1 == nullptr) {
return root2;
}
if(root2 == nullptr) {
return root1;
}
root = new TreeNode(root1->val + root2->val);
root->left = recursion(root1->left, root2->left, root);
root->right = recursion(root1->right, root2->right, root);
return root;
}
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
TreeNode* root = nullptr;
return recursion(root1, root2, root);
}
700.二叉搜索树中的搜索
思路:考二叉搜索树的概念、特性
TreeNode* searchBST(TreeNode* root, int val) {
if(root == nullptr) return root;
if(val == root->val)
return root;
if(val > root->val)
return searchBST(root->right, val);
if(val < root->val)
return searchBST(root->left, val);
return nullptr;
}
98.验证二叉搜索树
思路: 二叉搜索树左子树小于根节点小于右子树,符合中序遍历左根右递增,因此中序遍历二叉树,保存最大值,若当前元素<=最大值,返回false
long long maxVal = LONG_MIN; // 因为后台测试数据中有int最小值
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
bool left = isValidBST(root->left);
if(maxVal < root->val) maxVal = root->val;
else return false;
return left && isValidBST(root->right);
}