在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ We are given the Just as in the previous problem, the given tree was constructed from an list
Note that we were not given A directly, only a root node Suppose Return Example 1: Input: root = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]
Example 2: Input: root = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]
Example 3: Input: root = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]
Note:
最大树定义:一个树,其中每个节点的值都大于其子树中的任何其他值。 给出最大树的根节点 就像之前的问题那样,给定的树是从表
请注意,我们没有直接给定 A,只有一个根节点 假设 返回 示例 1: 输入:root = [4,1,3,null,null,2], val = 5 输出:[5,4,null,1,3,null,null,2] 解释:A = [1,4,2,3], B = [1,4,2,3,5] 示例 2: 输入:root = [5,2,4,null,1], val = 3 输出:[5,2,4,null,1,null,3] 解释:A = [2,1,5,4], B = [2,1,5,4,3] 示例 3: 输入:root = [5,2,3,null,1], val = 4 输出:[5,2,4,null,1,3] 解释:A = [2,1,5,3], B = [2,1,5,3,4] 提示:
Runtime: 16 ms
Memory Usage: 18.7 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 insertIntoMaxTree(_ root: TreeNode?, _ val: Int) -> TreeNode? { 16 var root = root 17 var X:TreeNode? = TreeNode(val) 18 if root == nil 19 { 20 return X 21 } 22 if root!.val < val 23 { 24 X!.left = root 25 return X 26 } 27 dfs(&root, X) 28 return root 29 } 30 31 func dfs(_ root: inout TreeNode?, _ X: TreeNode?) 32 { 33 if root!.right == nil || root!.right!.val < X!.val 34 { 35 var Y:TreeNode? = root!.right 36 root?.right = X 37 X?.left = Y 38 return 39 } 40 dfs(&root!.right, X) 41 } 42 } 16ms
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 insertIntoMaxTree(_ root: TreeNode?, _ val: Int) -> TreeNode? { 16 return constructMax(root, val) 17 } 18 19 func constructMax(_ root: TreeNode?, _ val: Int) -> TreeNode? { 20 guard let current = root else { return TreeNode(val) } 21 if val > current.val { 22 let newNode = TreeNode(val) 23 newNode.left = current 24 return newNode 25 } 26 current.right = constructMax(current.right, val) 27 return current 28 } 29 }
|
请发表评论