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

题目链接:654. 最大二叉树 - 力扣(LeetCode)

思路:跟中序后序构建二叉树思路类似

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """

        def createTree(nums):
            if len(nums) == 0:
                return None
            rootVal = max(nums)
            root = TreeNode(rootVal)
            index = 0
            for i in range(len(nums)):
                if nums[i] == rootVal:
                    index = i
            leftNums = nums[0:index]
            rightNums = nums[index+1:]
            root.left = createTree(leftNums)
            root.right = createTree(rightNums)
            return root
        
        return createTree(nums)

题目链接:617. 合并二叉树 - 力扣(LeetCode)

思路:以一个树为基础,另一个树在此基础上进行相加,其实就是树遍历的思路。

class Solution(object):
    def mergeTrees(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: TreeNode
        """
        def merge(root1, root2):
            if root1 == None:
                return root2
            if root2 == None:
                return root1

            root1.val += root2.val
            root1.left = merge(root1.left, root2.left)
            root1.right = merge(root1.right, root2.right)

            return root1

        return merge(root1, root2)

题目链接:700. 二叉搜索树中的搜索 - 力扣(LeetCode)

思路:二叉搜索树的正常思路

class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        index = root
        while index != None:
            if index.val == val:
                return index
            if val > index.val:
                index = index.right
            elif val < index.val:
                index = index.left
        

        if index == None:
            return None

题目链接:98. 验证二叉搜索树 - 力扣(LeetCode)

思路:中序遍历若是递增则是二叉搜索树

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.result = True
        self.temp = 0
        self.first = True #第一次不作判断
        def travel(root):
            if root == None:
                return

            travel(root.left)

            if self.first == True:
                self.temp = root.val
                self.first = False
            else:
                if root.val > self.temp:
                    self.temp = root.val
                else:
                    self.result = False
                    

            travel(root.right)

        travel(root)

        return self.result

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值