LeetCode 538 把二叉搜索树转换为累加树

mac2022-06-30  17

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

例如:

输入: 二叉搜索树:               5             /   \            2     13

输出: 转换为累加树:              18             /   \           20     13

Js

/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var convertBST = function(root) { num = 0 function dfs(root){ if (!root) { return null } dfs(root.right) num += root.val root.val = num dfs(root.left) return root } return dfs(root) }

Py

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def convertBST(self, root: TreeNode) -> TreeNode: self.a = 0 def dfs(root): if not root: return None dfs(root.right) self.a+=root.val root.val = self.a dfs(root.left) return root return dfs(root)

 

最新回复(0)