1. 程式人生 > 實用技巧 >LeetCode | 1038. 把二叉搜尋樹轉換為累加樹【Python】

LeetCode | 1038. 把二叉搜尋樹轉換為累加樹【Python】

Problem

LeetCode

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/

Example 1:

Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

Example 2:

Input: root = [0,null,1]
Output: [1,null,1]

Example 3:

Input: root = [1,0,2]
Output: [3,3,2]

Example 4:

Input: root = [3,2,4,1]
Output: [7,9,4,10]

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • 0 <= Node.val <= 100
  • All the values in the tree are unique.
  • root is guaranteed to be a valid binary search tree.

問題

力扣

給出二叉 搜尋 樹的根節點,該樹的節點值各不相同,請你將其轉換為累加樹(Greater Sum Tree),使每個節點 node 的新值等於原樹中大於或等於 node.val 的值之和。

提醒一下,二叉搜尋樹滿足下列約束條件:

  • 節點的左子樹僅包含鍵 小於 節點鍵的節點。
  • 節點的右子樹僅包含鍵 大於 節點鍵的節點。
  • 左右子樹也必須是二叉搜尋樹。

注意:該題目與 538: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/ 相同

示例 1:

輸入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
輸出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

示例 2:

輸入:root = [0,null,1]
輸出:[1,null,1]

示例 3:

輸入:root = [1,0,2]
輸出:[3,3,2]

示例 4:

輸入:root = [3,2,4,1]
輸出:[7,9,4,10]

提示:

  • 樹中的節點數介於 1100 之間。
  • 每個節點的值介於 0100 之間。
  • 樹中的所有值 互不相同
  • 給定的樹為二叉搜尋樹。

思路

中序遍歷

利用 BST 的中序遍歷就是升序的特性,降序遍歷 BST 的元素值。

Python3 程式碼

# 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 bstToGst(self, root: TreeNode) -> TreeNode:
        def dfs(root):
            nonlocal sumval
            if root:
                dfs(root.right)
                sumval += root.val
                root.val = sumval  # 將BST轉化成累加樹
                dfs(root.left)
        
        sumval = 0
        dfs(root)
        return root

GitHub 連結

Python