程式碼隨想錄演算法訓練營第23天 | 669. 修剪二叉搜尋樹、108.將有序陣列轉換為二叉搜尋樹、538.把二叉搜尋樹轉換為累加樹

哆啦**發表於2024-07-16

程式碼隨想錄演算法訓練營第22天 | 669. 修剪二叉搜尋樹、108.將有序陣列轉換為二叉搜尋樹、538.把二叉搜尋樹轉換為累加樹

  1. 修剪二叉搜尋樹:https://leetcode.cn/problems/trim-a-binary-search-tree/description/
    程式碼隨想錄:
    https://programmercarl.com/0669.修剪二叉搜尋樹.html#演算法公開課
    108.將有序陣列轉換為二叉搜尋樹
    https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/
    程式碼隨想錄:
    https://programmercarl.com/0108.將有序陣列轉換為二叉搜尋樹.html#演算法公開課
    538.把二叉搜尋樹轉換為累加樹
    https://leetcode.cn/problems/convert-bst-to-greater-tree/
    程式碼隨想錄:
    https://programmercarl.com/0538.把二叉搜尋樹轉換為累加樹.html

669. 修剪二叉搜尋樹

題解思路

  • 遞迴法:判斷當前節點是否符合要求;刪除當下節點;
  • 迭代法:(不需要用棧遍歷)
    1. 將root移動至區間內
    2. 修剪左子樹
    3. 修剪右子樹
class Solution:
    def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        if not root:
            return root
        if root.val<low:
            root = root.right
            return self.trimBST(root,low,high)
        elif root.val>high:
            root = root.left
            return self.trimBST(root,low,high)
        root.left = self.trimBST(root.left,low,high)
        root.right = self.trimBST(root.right,low,high)
        return root
class Solution:
    def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        if not root:
            return root
        while root and root.val<low:
            root = root.right
        while root and root.val>high:
            root = root.left
        curr = root
        while curr:
            while curr.left and curr.left.val<low:
                curr.left = curr.left.right
            curr = curr.left

        curr = root
        while curr:
            while curr.right and curr.right.val>high:
                curr.right = curr.right.left
            curr = curr.right
        return root

108.將有序陣列轉換為二叉搜尋樹

題解思路

  • 平衡二叉樹:從中間節點開始劃分陣列;
  • 遞迴法:每次選取中間節點、遞迴模擬賦值即可;
  • 迭代法:3個佇列模擬選取節點和賦值的過程;

題解程式碼

遞迴法

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums)==0:
            return None
        middle_nums = len(nums)//2
        node = TreeNode(nums[middle_nums])
        node.left = self.sortedArrayToBST(nums[:middle_nums])
        node.right = self.sortedArrayToBST(nums[middle_nums+1:])
        return node

迭代法

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums)==0:
            return None
        root = TreeNode(0)
        node_que = collections.deque([root])
        left_que = collections.deque([0])
        right_que = collections.deque([len(nums)-1])

        while node_que:
            curr_node = node_que.popleft()
            left = left_que.popleft()
            right =right_que.popleft()
            mid = left+(right-left)//2
            curr_node.val = nums[mid]

            if left<=mid-1:
                curr_node.left = TreeNode(0)
                node_que.append(curr_node.left)
                left_que.append(left)
                right_que.append(mid-1)
            if right>=mid+1:
                curr_node.right = TreeNode(0)
                node_que.append(curr_node.right)
                left_que.append(mid+1)
                right_que.append(right)
        return root

538.把二叉搜尋樹轉換為累加樹

題解思路

  • 遞迴法:先計算每個右子樹。每個值等於前一個值累加;
  • 迭代法:
    • 採用棧 將所有右節點進入棧,依次遍歷其左子樹
    • 記錄self.pre
class Solution:
    def __init__(self):
        self.pre = 0
    def trans(self,curr):
        if not curr:
            return None
        self.trans(curr.right)
        curr.val = curr.val+self.pre
        self.pre = curr.val
        self.trans(curr.left)
        return curr
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        return self.trans(root)
class Solution:
    def __init__(self):
        self.pre = 0

    def trans(self,root):
        if not root:
            return None

        st = []
        curr = root
        while st or curr:
            if curr:
                st.append(curr)
                curr = curr.right
            else:
                curr = st.pop()
                curr.val = curr.val+self.pre
                self.pre = curr.val
                curr = curr.left

    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        self.trans(root)
        return root

相關文章