Day20 | 654.最大二叉樹 、 617.合併二叉樹 、 700.二叉搜尋樹中的搜尋 98.驗證二叉搜尋樹

forrestr發表於2024-06-15

654.最大二叉樹

又是構造二叉樹,昨天大家剛剛做完 中序後序確定二叉樹,今天做這個 應該會容易一些, 先看影片,好好體會一下 為什麼構造二叉樹都是 前序遍歷

題目連結/文章講解:https://programmercarl.com/0654.最大二叉樹.html
影片講解:https://www.bilibili.com/video/BV1MG411G7ox

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums) == 0:
            return None
        max_num = max(nums)
        max_index = nums.index(max_num)
        left_nums = nums[0:max_index]
        right_nums = nums[max_index+1:]
        
        root = TreeNode(nums[max_index])
        root.left = self.constructMaximumBinaryTree(left_nums)
        root.right = self.constructMaximumBinaryTree(right_nums)
        return root

617.合併二叉樹

這次是一起操作兩個二叉樹了, 估計大家也沒一起操作過兩個二叉樹,也不知道該如何一起操作,可以看影片先理解一下。 優先掌握遞迴。

題目連結/文章講解:https://programmercarl.com/0617.合併二叉樹.html
影片講解:https://www.bilibili.com/video/BV1m14y1Y7JK

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if root1 is None and root2:
            val = root2.val
            root = TreeNode(val)
            root.left = self.mergeTrees(None,root2.left)
            root.right = self.mergeTrees(None,root2.right)
        elif root2 is None and root1:
            val = root1.val
            root = TreeNode(val)
            root.left = self.mergeTrees(root1.left,None)
            root.right = self.mergeTrees(root1.right,None)
        elif root1 and root2:
            val = root1.val+root2.val
            root = TreeNode(val)
            root.left = self.mergeTrees(root1.left,root2.left)
            root.right = self.mergeTrees(root1.right,root2.right)
        else:
            return None
        return root

上面的程式碼太冗餘了,如果一個數的節點的為空時,直接返回另外一個數的對應節點就好了,不需要再重複地去遞迴構建了。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if root1 is None and root2:
            return root2
        elif root2 is None and root1:
            return root1
        elif root1 and root2:
            val = root1.val+root2.val
            root = TreeNode(val)
            root.left = self.mergeTrees(root1.left,root2.left)
            root.right = self.mergeTrees(root1.right,root2.right)
            return root
        else:
            return None

700.二叉搜尋樹中的搜尋

遞迴和迭代 都可以掌握以下,因為本題比較簡單, 瞭解一下 二叉搜尋樹的特性

題目連結/文章講解: https://programmercarl.com/0700.二叉搜尋樹中的搜尋.html
影片講解:https://www.bilibili.com/video/BV1wG411g7sF

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        while root:
            if root.val == val:
                return root
            elif root.val < val:
                root = root.right
            else:
                root = root.left
        return None

98.驗證二叉搜尋樹

遇到 搜尋樹,一定想著中序遍歷,這樣才能利用上特性。

但本題是有陷阱的,可以自己先做一做,然後在看題解,看看自己是不是掉陷阱裡了。這樣理解的更深刻。

題目連結/文章講解:https://programmercarl.com/0098.驗證二叉搜尋樹.html
影片講解:https://www.bilibili.com/video/BV18P411n7Q4

思考

1.中序遍歷判斷是否是遞增的。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
def traversal(root,path):
    if root is None:
        return
    traversal(root.left,path)
    path.append(root.val)
    traversal(root.right,path)
class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        path = []
        traversal(root,path)
        print(path)
        for i in range(1,len(path)):
            if path[i] <= path[i-1]:
                return False
        return True

2.遞迴法

class Solution:
    def __init__(self):
        self.maxVal = float('-inf')  # 因為後臺測試資料中有int最小值

    def isValidBST(self, root):
        if root is None:
            return True

        left = self.isValidBST(root.left)
        # 中序遍歷,驗證遍歷的元素是不是從小到大
        if self.maxVal < root.val:
            self.maxVal = root.val
        else:
            return False
        right = self.isValidBST(root.right)

        return left and right

相關文章