在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given the root of a binary search tree with distinct values, modify it so that every As a reminder, a binary search tree is a tree that satisfies these constraints:
Example 1: 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:
给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 提醒一下,二叉搜索树满足下列约束条件:
示例: 输入:[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] 提示:
Runtime: 8 ms
Memory Usage: 19.2 MB
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 } 8ms 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 }
|
请发表评论