• 算法day20|654,617,700,98


    654. Maximum Binary Tree

    我的代码:但是出错了,但是大概的思路是对的!得出结论,终止条件设置错误,if nums 为0

    1. class Solution:
    2. def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
    3. #设置最大根节点
    4. if root is None:
    5. return None
    6. root_val = max(nums)
    7. root_index = nums.index(root_val)
    8. root = TreeNode(root_val)
    9. #找左边区间
    10. left_intervel = nums[:root_index]
    11. #找右边区间
    12. right_intervel = nums[root_index+1:]
    13. #左节点,找下一个大的
    14. root.left = self.constructMaximumBinaryTree(left_intervel)
    15. #右节点,找
    16. root.right = self.constructMaximumBinaryTree(right_intervel)
    17. return root

    构造二叉树系列的题目,需要使用前序遍历来构造二叉树。

    什么时候要在左右遍历那个地方写if语句?需要根据终止条件来判断,

    1. class Solution:
    2. def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
    3. #终止条件
    4. if not nums:
    5. return None
    6. #中
    7. #存入最大值
    8. max_val = max(nums)
    9. max_index = nums.index(max_val)
    10. root = TreeNode(max_val)
    11. #左节点,找下一个大的
    12. #找左边区间
    13. left_interval = nums[:max_index]
    14. root.left = self.constructMaximumBinaryTree(left_interval)
    15. #右节点
    16. #找右边区间
    17. right_interval = nums[max_index+1:]
    18. root.right = self.constructMaximumBinaryTree(right_interval)
    19. #返回值
    20. return root

     二刷:使用js(未ac)

    1. var constructMaximumBinaryTree = function(nums) {
    2. if(nums.length === 0){
    3. return null
    4. }
    5. const rootNode = Math.max(...nums);
    6. console.log(rootNode);
    7. const rootIndex = nums.indexOf(rootNode);
    8. const root = new TreeNode(rootNode);
    9. let left = nums.slice(0,rootIndex);
    10. console.log(left);
    11. let right = nums.slice(rootIndex+1);
    12. console.log(right);
    13. root.left = constructMaximumBinaryTree(left);
    14. root.right = constructMaximumBinaryTree(right);
    15. return root
    16. };

    三刷

    1. var constructMaximumBinaryTree = function(nums) {
    2. if(!nums.length) return null
    3. let root = Math.max(...nums)
    4. let index = nums.indexOf(root)
    5. const tree = new TreeNode(root)
    6. tree.left = constructMaximumBinaryTree(nums.slice(0,index))
    7. tree.right = constructMaximumBinaryTree(nums.slice(index+1))
    8. return tree
    9. };

     

     617. Merge Two Binary Trees

    合并二叉树

    合并到第一棵树上

    1. class Solution:
    2. def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
    3. #终止条件,当节点为空的时候,返回所对应的另一个树的值.因为他们是同步遍历的
    4. if root1 is None: return root2
    5. if root2 is None: return root1
    6. #中序遍历
    7. root1.val += root2.val
    8. #左
    9. root1.left = self.mergeTrees(root1.left,root2.left)
    10. #右
    11. root1.right = self.mergeTrees(root1.right,root2.right)
    12. #返回值,我们将二叉树合并到第一个树
    13. return root1

    合并到 新的树上

    1. class Solution:
    2. def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
    3. #终止条件,当节点为空的时候,返回所对应的另一个树的值.因为他们是同步遍历的
    4. if root1 is None: return root2
    5. if root2 is None: return root1
    6. #中序遍历
    7. #创建新的树
    8. newtree = TreeNode(0)
    9. newtree.val = root1.val + root2.val
    10. #左
    11. newtree.left = self.mergeTrees(root1.left,root2.left)
    12. #右
    13. newtree.right = self.mergeTrees(root1.right,root2.right)
    14. #返回值,我们将二叉树合并到第一个树
    15. return newtree

     二刷:(未ac)

    1. var mergeTrees = function(root1, root2) {
    2. // 有一棵的树为空,直接返回不为空的节点
    3. if(root1 === null){
    4. return root2
    5. }
    6. if(root2 === null){
    7. return root1
    8. }
    9. let que = []
    10. que.push(root1)
    11. que.push(root2)
    12. while(que.length != 0){
    13. let node1 = que.shift();
    14. let node2 = que.shift();
    15. //
    16. node1.val += node2.val;
    17. if(node1.left != null && node2.left != null){
    18. que.push(node1.left);
    19. que.push(node2.left);
    20. }
    21. if(node1.right != null && node2.right != null){
    22. que.push(node1.right)
    23. que.push(node2.right)
    24. }
    25. if(node1.left === null && node2.left != null){
    26. node1.left = node2.left
    27. }
    28. if(node1.right === null && node2.right != null){
    29. node1.right = node2.right
    30. }
    31. }
    32. return root1
    33. };

    700. Search in a Binary Search Tree

    二叉搜索树的特征:                                                                     根节点比左子树的所有值都大,                                           比右子树的所有值都小

    递归法:

    1. class Solution:
    2. def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
    3. #终止条件 当根节点为空,返回root,或者当根节点的值为val的值
    4. if root is None or root.val == val:return root
    5. #创建一个节点,接住返回的指针.左子树如果搜索到了val,要将该节点返回。 如果不用一个变量将其接住,那么返回值不就没了。
    6. result = TreeNode()
    7. #如果val的值比根的大,往右(二叉搜索的特性)
    8. if val>root.val:
    9. result = self.searchBST(root.right,val)
    10. if val < root.val:
    11. result = self.searchBST(root.left,val)
    12. return result

    迭代法:

    1. class Solution:
    2. def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
    3. #迭代法
    4. while root:
    5. if val > root.val:
    6. root = root.right
    7. elif val
    8. root = root.left
    9. else:
    10. return root

     二刷(未ac)

    递归法。我忘记return值,所以一直报错

    1. var searchBST = function(root, val) {
    2. //遍历到根节点了,返回null值,终止遍历
    3. if(root === null){
    4. return null;
    5. }
    6. // 如果找到了值,返回root
    7. if(root.val === val){
    8. return root;
    9. }
    10. // 如果在左子树找到了相应的值,要记得返回,不要忘记return的值
    11. if(root.val > val){
    12. return searchBST(root.left,val);
    13. }
    14. if(root.val < val){
    15. return searchBST(root.right,val);
    16. }
    17. // 如果什么都没找到的话,返回null
    18. return null
    19. };

     迭代法,使用二叉树特性

    1. var searchBST = function(root, val) {
    2. while(root !== null){
    3. if(root.val < val){
    4. root = root.right;
    5. }else if(root.val > val){
    6. root = root.left;
    7. }else{
    8. return root;
    9. }
    10. }
    11. return null;
    12. };

    三刷

    1. var searchBST = function(root, val) {
    2. const traversal = function(node, val) {
    3. if (node === null) {
    4. return null;
    5. }
    6. if (node.val === val) {
    7. return node;
    8. } else if (node.val > val) {
    9. return traversal(node.left, val);
    10. } else {
    11. return traversal(node.right, val);
    12. }
    13. }
    14. return traversal(root, val);
    15. };

     

    98. Validate Binary Search Tree

    需要去验证二叉搜索树,如果遍历完,元素都是递增的,那么就是二叉搜索树

    如果是空节点 是不是二叉搜索树呢?是的,二叉搜索树也可以为空

    第一种想法:

    递归二叉树,将值保存到数组中,如果数组是单调递增的,那么就是二叉搜索树

    第二种:

    递归二叉树,直接遍历二叉树是不是单调递增

    1. def isValidBST(self, root: TreeNode) -> bool:
    2. cur_max = -float("INF")
    3. def _isValidBST(root: TreeNode) -> bool:
    4. nonlocal cur_max
    5. #终止条件
    6. if not root:return True
    7. #左
    8. left = _isValidBST(root.left)
    9. #中
    10. if root.val> cur_max:
    11. cur_max = root.val
    12. else:
    13. return False
    14. #右
    15. right = _isValidBST(root.right)
    16. #如果左子树满足条件,右子树也满足条件
    17. return left and right
    18. return _isValidBST(root)

    代码误区:(我就是那么做的)

    if (root.left is not None) and (root.right is not None) and (root.val > root.left.val) and (root.val < root.right.val): return True

    判断根节点是不是比左节点大,比右节点小。很容易陷入误区。因为根节点需要比左子树的所有值都小。要比右子树所有值都大。

    第三种:

    递归二叉树,直接遍历二叉树是不是单调递增,这里使用指针优化

    Non-local的使用:

    1. count = 1
    2. def a():
    3. count = 'a函数里面'   #如果不事先声明,那么函数b中的nonlocal就会报错
    4. def b():
    5. nonlocal count
    6. print(count)
    7. count = 2
    8. b()
    9. print(count)
    10. if __name__ == '__main__':
    11. a()
    12. print(count)

     下面会报错:

    1. count = 1
    2. def a():
    3. #nonlocal count #这种声明方法肯定报错,
    4. def b():
    5. nonlocal count #在a()函数中没有提前声明,所以报错
    6. print(count)
    7. count = 2
    8. b()
    9. print(count)
    10. if __name__ == '__main__':
    11. a()
    12. print(count)



    Python3 中的nonlocal用法 - 希望中追寻 - 博客园

    定义负无穷怎么定义:

    cur = -float("INF")

     二刷:(未ac)使用双指针用法

    1. var isValidBST = function (root) {
    2. let pre = null;
    3. const inOrder = function (node) {
    4. if (node === null)
    5. return true;
    6. let left = inOrder(node.left);
    7. if (pre !== null && pre.val >= node.val)
    8. return false;
    9. pre = node;
    10. let right = inOrder(node.right);
    11. return left && right;
    12. }
    13. return inOrder(root);
    14. };

  • 相关阅读:
    Sora引领AI生成模型新篇章,视频人工AI创造新视野
    【流式传输】使用Spring Boot实现ChatGpt流式传输
    el-input一些校验 & 事件
    轻量级CI/CD发布部署环境搭建及使用_01_基本介绍
    40个高质量ssm+vue毕设项目分享【源码+论文】(一)
    数据结构与算法课后题-第二章(顺序表)
    五.指针与结构体
    2024年大语言模型的微调
    NAT 技术概览(二)
    黑苹果修改三码步骤
  • 原文地址:https://blog.csdn.net/weixin_42173016/article/details/127851614