您的位置:首页 > 教育 > 锐评 > 代码随想录训练营第十七天|654.最大二叉树 、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

代码随想录训练营第十七天|654.最大二叉树 、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

2024/10/5 18:26:29 来源:https://blog.csdn.net/qq_43487696/article/details/141817425  浏览:    关键词:代码随想录训练营第十七天|654.最大二叉树 、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

Leetcode654.最大二叉树

题目链接:654. 最大二叉树

Python:

class Solution:def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:if len(nums) == 1:node = TreeNode(nums[0])return nodemaxvalue, index = 0, 0for i in range(len(nums)):if nums[i] > maxvalue:maxvalue = nums[i]index = iroot = TreeNode(maxvalue)if index > 0:leftnums = nums[:index]root.left = self.constructMaximumBinaryTree(leftnums)if index < len(nums) - 1:rightnums = nums[index+1:]root.right = self.constructMaximumBinaryTree(rightnums)return root

Leetcode617.合并二叉树

题目链接:617. 合并二叉树

C++:

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;}
};

Leetcode700.二叉搜索树中的搜索

题目链接:700. 二叉搜索树中的搜索

C++:(迭代法)

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;elsereturn root;}return nullptr;}
};

Python:(递归)

class Solution:def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:if root == None or root.val == val:return rootresult = Noneif root.val > val:result = self.searchBST(root.left, val)if root.val < val:result = self.searchBST(root.right, val)return result

Leetcode98.验证二叉搜索树

题目链接:98. 验证二叉搜索树

C++:

class Solution {
public:TreeNode* pre = nullptr; // 用来记录前一个节点bool isValidBST(TreeNode* root) {if(root == nullptr) return true;bool sousuo_left = isValidBST(root->left);//中序遍历if(pre != nullptr && pre->val >= root->val)return false;pre = root;bool sousuo_right = isValidBST(root->right);return sousuo_left && sousuo_right;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com