★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-hkategqv-mc.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given the root of a binary search tree with distinct values, modify it so that every node
has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val
.node
As a reminder, a binary search tree is a tree that satisfies these constraints:git
Example 1:github
Input: [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]
Note:微信
1
and 100
.0
and 100
.給出二叉搜索樹的根節點,該二叉樹的節點值各不相同,修改二叉樹,使每一個節點 node
的新值等於原樹的值之和,這個值應該大於或等於 node.val
。less
提醒一下,二叉搜索樹知足下列約束條件:spa
示例:code
輸入:[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]
提示:htm
1
和 100
之間。0
和 100
之間。1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func bstToGst(_ root: TreeNode?) -> TreeNode? { 16 var root = root 17 var acc:Int = 0 18 dfs(&root,&acc) 19 return root 20 } 21 22 func dfs(_ node:inout TreeNode?,_ acc:inout Int) 23 { 24 if node != nil 25 { 26 dfs(&node!.right, &acc) 27 var temp:Int = node!.val 28 node!.val += acc 29 acc += temp 30 dfs(&node!.left, &acc) 31 } 32 } 33 }
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 var sum = 0; 16 func bstToGst(_ root: TreeNode?) -> TreeNode? { 17 18 guard let rootd = root else {return nil} 19 bstToGst(rootd.right); 20 rootd.val += sum; 21 sum = rootd.val; 22 bstToGst(rootd.left); 23 return rootd 24 25 } 26 }