Problem
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:
image
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.
問(wèn)題
給出二叉 搜索 樹(shù)的根節(jié)點(diǎn)梨睁,該樹(shù)的節(jié)點(diǎn)值各不相同,請(qǐng)你將其轉(zhuǎn)換為累加樹(shù)(Greater Sum Tree)鸵膏,使每個(gè)節(jié)點(diǎn) node 的新值等于原樹(shù)中大于或等于 node.val 的值之和脉让。
提醒一下,二叉搜索樹(shù)滿(mǎn)足下列約束條件:
- 節(jié)點(diǎn)的左子樹(shù)僅包含鍵 小于 節(jié)點(diǎn)鍵的節(jié)點(diǎn)。
- 節(jié)點(diǎn)的右子樹(shù)僅包含鍵 大于 節(jié)點(diǎn)鍵的節(jié)點(diǎn)。
- 左右子樹(shù)也必須是二叉搜索樹(shù)蒲肋。
注意:該題目與 538: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/ 相同
示例 1:
image
輸入:[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]
提示:
- 樹(shù)中的節(jié)點(diǎn)數(shù)介于
1
和100
之間。 - 每個(gè)節(jié)點(diǎn)的值介于
0
和100
之間钝满。 - 樹(shù)中的所有值 互不相同 兜粘。
- 給定的樹(shù)為二叉搜索樹(shù)。
思路
中序遍歷
利用 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轉(zhuǎn)化成累加樹(shù)
dfs(root.left)
sumval = 0
dfs(root)
return root