在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ We are given the head node Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. (Recall that the subtree of a node X is X, plus every node that is a descendant of X.) Example 1: Input: [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer. Example 2: Input: [1,0,1,0,0,0,1] Output: [1,null,1,null,1] Example 3: Input: [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1] Note:
给定二叉树根结点 返回移除了所有不包含 1 的子树的原二叉树。 ( 节点 X 的子树为 X 本身,以及所有 X 的后代。) 示例1: 输入: [1,null,0,0,1] 输出: [1,null,0,null,1] 解释: 只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。 示例2: 输入: [1,0,1,0,0,0,1] 输出: [1,null,1,null,1] 示例3: 输入: [1,1,0,1,1,0,1,0] 输出: [1,1,0,1,1,null,1] 说明:
Runtime: 8 ms
Memory Usage: 19.3 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 pruneTree(_ root: TreeNode?) -> TreeNode? { 16 if root == nil {return nil} 17 root?.left = pruneTree(root?.left) 18 root?.right = pruneTree(root?.right) 19 return (root?.left == nil && root?.right == nil && root!.val == 0) ? nil : root 20 } 21 } 12ms 1 class Solution { 2 func pruneTree(_ root: TreeNode?) -> TreeNode? { 3 _ = helper(root) 4 return root 5 } 6 7 func helper(_ root: TreeNode?) -> Int { 8 guard let root = root else { 9 return 0 10 } 11 let left = helper(root.left) 12 let right = helper(root.right) 13 if left == 0 { 14 root.left = nil 15 } 16 if right == 0 { 17 root.right = nil 18 } 19 return root.val + left + right 20 } 21 } 16ms 1 class Solution { 2 private class item { 3 var node: TreeNode 4 var toVisit: Bool 5 var parent: TreeNode 6 var dir: Bool //left: false, right: true 7 8 init(_ node: TreeNode, _ toVisit: Bool, _ parent: TreeNode, _ dir: Bool) { 9 self.node = node 10 self.toVisit = toVisit 11 self.parent = parent 12 self.dir = dir 13 } 14 } 15 16 func pruneTree(_ root: TreeNode?) -> TreeNode? { 17 guard let root = root else { return nil } 18 let fake = TreeNode(-1); fake.left = root 19 20 var stack = [item(root,true,fake,false)] 21 22 while !stack.isEmpty { 23 let top = stack.last! 24 if top.toVisit { 25 let tmp = top.node 26 if (tmp.left != nil) { 27 stack.append(item(tmp.left!,true,tmp,false)) 28 } 29 if (tmp.right != nil) { 30 stack.append(item(tmp.right!,true,tmp,true)) 31 } 32 top.toVisit = false 33 } else { 34 let tmp = top.node 35 if (tmp.left == nil && tmp.right == nil && tmp.val == 0) { 36 if top.dir { 37 top.parent.right = nil 38 } else { 39 top.parent.left = nil 40 } 41 } 42 stack.removeLast(1) 43 } 44 } 45 46 return fake.left 47 } 48 }
|
请发表评论