首页 > 编程语言 >代码随想录训练营第二十天打卡(Python)| 654.最大二叉树 、617.合并二叉树 、700.二叉搜索树中的搜索 、98.验证二叉搜索树

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

时间:2023-10-30 22:56:09浏览次数:33  
标签:return val max self 二叉 搜索 二叉树 root left

654.最大二叉树
1、使用切片

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums) == 0:
            return None
        max_val = max(nums)
        max_index = nums.index(max_val)
        node = TreeNode(max_val)
        node.left = self.constructMaximumBinaryTree(nums[:max_index])
        node.right = self.constructMaximumBinaryTree(nums[max_index+1:])
        return node

2、基础版

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums) == 1:
            return TreeNode(nums[0])
        max_val = 0
        max_index = 0
        for i in range(len(nums)):
            if nums[i] > max_val:
                max_val = nums[i]
                max_index = i

        node = TreeNode(max_val)
        if max_index > 0:
            node.left = self.constructMaximumBinaryTree(nums[:max_index])
        if max_index < len(nums) - 1:
            node.right = self.constructMaximumBinaryTree(nums[max_index+1:])
        return node

3、下标法

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        return self.buildTree(nums, 0, len(nums))

    def buildTree(self, nums, left, right):
        if left >= right:
            return None
        max_val = nums[left]
        max_index = left
        for i in range(left+1, right):
            if nums[i] > max_val:
                max_val = nums[i]
                max_index = i
        node = TreeNode(max_val)
        node.left = self.buildTree(nums, left, max_index)
        node.right = self.buildTree(nums, max_index+1, right)
        return node

617.合并二叉树
1、前序遍历

class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root1:
            return root2
        if not root2:
            return root1
        node = TreeNode(root1.val+root2.val)
        node.left = self.mergeTrees(root1.left, root2.left)
        node.right = self.mergeTrees(root1.right, root2.right)
        return node

2、迭代法

from collections import deque
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root1 and not root2:
            return None
        if not root1:
            return root2
        if not root2:
            return root1

        queue = deque()
        queue.append(root1)
        queue.append(root2)
        while queue:
            node1 = queue.popleft()
            node2 = queue.popleft()
            if node1.left and node2.left:
                queue.append(node1.left)
                queue.append(node2.left)
            if node1.right and node2.right:
                queue.append(node1.right)
                queue.append(node2.right)

            node1.val = node1.val + node2.val
            if not node1.left and node2.left:
                node1.left = node2.left
            if not node1.right and node2.right:
                node1.right = node2.right

        return root1

700.二叉搜索树中的搜索

1、递归法

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root is None:
            return None
        if root.val == val:
            return root
        if root.val > val:
            return self.searchBST(root.left, val)
        else:
            return self.searchBST(root.right, val)

2、迭代法

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        while root:
            if root.val > val:
                root = root.left
            elif root.val < val:
                root = root.right
            else:
                return root
        return None

98.验证二叉搜索树
思路: 二叉搜索树的中序遍历是递增的
1、设定最大的极小值递归法

class Solution:
    def __init__(self):
        self.max_val = float('-inf')

    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True
        left = self.isValidBST(root.left)
        if self.max_val < root.val:
            self.max_val = root.val
        else:
            return False
        right = self.isValidBST(root.right)
        return left and right

2、记录前一个节点的递归法

class Solution:
    def __init__(self):
        self.pre = None # 记录前一个节点

    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True
        left = self.isValidBST(root.left)
        if self.pre and self.pre.val >= root.val:
            return False
        self.pre = root
        right = self.isValidBST(root.right)
        return left and right

3、迭代法

class Solution:

    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True
        stack = []
        res = []
        cur, pre = root, None # cur指向跟节点,pre 记录前一个节点
        while cur or stack:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                if pre and pre.val >= cur.val:
                    return False
                pre = cur
                cur = cur.right
        return True

标签:return,val,max,self,二叉,搜索,二叉树,root,left
From: https://www.cnblogs.com/yixff/p/17799087.html

相关文章

  • codeforces 1829G. Hits Different 容斥原理+记忆化搜索
    题目描述:给定一个n,把n给打倒,然后递归的求出包含n在内的上面所有的会倒下的瓶子值的平方和。这里使用二分先求出目前给定的n的行号i和列号j。观察可以发现,对于所有的列号j,j=1或者j=i时,是需要考虑往上单边的总和,其他情况都有两个分支。再观察可以发现,两个分支在再上一行的重合部......
  • python采集京东app搜索商品数据(2023-10-30)
    摘要:   python采集京东app搜索商品数据(2023-10-30)一、技术要点: 1、cookie可以从手机app端用charles抓包获取; 2、无需安装nodejs,纯python源码; 3、搜索接口为:functionId=search; 4、clientVersion="10.1.4"同时也支持更高的版本; 5、sign签名算法已转成pyth......
  • 浅谈搜索展现层场景化技术-tanGo实践 算子化
    浅谈搜索展现层场景化技术-tanGo实践https://mp.weixin.qq.com/s/nVy9SYRIaaqZWgOHKTMQ4Qintroduction本文为搜索展现层相关技术,主线会先通过介绍搜索阿拉丁的产品形态,让读者初步了解什么是阿拉丁,及相关展现概念。之后会聚焦场景化产品,场景化是搜索构建沉浸式完美体验(重新组合整......
  • C#搜索注册表
    stringkeyPath=@"Software\***\***";stringvalueName="ValueName";using(Microsoft.Win32.RegistryKeykey=Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyPath)){......
  • QTreeWidget 的搜索实时显示功能
    QTreeWidget的子条目很多时候需要提供实时的搜索功能,以便能快速找到所需要的条目。代码如下://1.创建当输入框文本变化时的信号槽。connect(ui.lineEditSearch,&QLineEdit::textChanged,this,&Demo01_GUI::OnFindItem);//2.槽函数实现检索时,实时显示符合要求的QTre......
  • "阿里巴巴按关键字搜索接口:一键获取海量商品信息,助力商家抢占市场先机!"
    阿里巴巴按关键字搜索商品的接口是通过开放平台提供的API接口来实现的。要使用这个接口,需要进行以下步骤:确认API接口的请求地址和所需参数:需要先查看API文档,了解所要访问的API接口的请求地址和请求参数,以便正确地构造请求和获取数据。注册一个apikey和apisecret调用接入。使用apike......
  • 代码随性训练营第十七天(Python)| 110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之
    110.平衡二叉树1、递归法classSolution:defisBalanced(self,root:Optional[TreeNode])->bool:ifself.get_height(root)!=-1:#-1代表高度差大于1returnTrueelse:returnFalsedefget_height(self,root):......
  • 象棋(搜索+优化)
    Lutece(uestc.edu.cn)哦突然想起来这个搜索叫启发式搜索......#include"bits/stdc++.h"usingnamespacestd;chars[10][10];intdx[8]={-2,-2,-1,-1,1,1,2,2};intdy[8]={-1,1,-2,2,-2,2,-1,1};intans;charss[6][6]={"11111","01111","00*11......
  • 谷歌搜索引擎课程笔记
    1、bywave、lantem搜索引擎处理流程GoogleHackingDatabase:GHDB汇总了数千条谷歌搜索高级语法,涵盖了立足点、敏感路径、敏感文件、错误信息、漏洞文件、漏洞服务器、Web服务器检测等方方面面。2004年开始更名为GHDB,现在由网站exploit-db.com维护GoogleHacking操作符基础操作符:......
  • 二叉搜索树结构分析
    二叉查找树(BinarySearchTree),(又:二叉搜索树,二叉排序树),它具有以下特点:若任一节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若任一节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;任意节点的左、右子树也分别为二叉查找树;没有键值相等的节点。下......