在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. For example, Given the tree: 4 / \ 2 7 / \ 1 3 And the value to search: 2 You should return this subtree: 2 / \ 1 3 In the example above, if we want to search the value Note that an empty tree is represented by 给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 例如, 给定二叉搜索树: 4 / \ 2 7 / \ 1 3 和值: 2 你应该返回如下子树: 2 / \ 1 3 在上述示例中,如果要找的值是 Runtime: 168 ms
Memory Usage: 19.6 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 searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? { 16 var root = root 17 while ((root != nil) && root!.val != val) 18 { 19 root = (root!.val > val) ? root?.left : root?.right 20 } 21 return root 22 } 23 } 168ms 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 searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? { 16 if nil == root { 17 return nil 18 } else{ 19 let value = (root?.val)! 20 if value == val { 21 return root 22 } else if value < val { 23 return searchBST(root?.right, val) 24 } else { 25 return searchBST(root?.left, val) 26 } 27 } 28 } 29 } 188ms 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 searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? { 16 guard root != nil else { return nil } 17 var current = root 18 while current != nil { 19 if current!.val == nil { return nil } 20 if current!.val == val { return current } 21 if val > current!.val { 22 current = current!.right 23 } else { 24 current = current!.left 25 } 26 } 27 return nil 28 } 29 }
|
请发表评论