★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-youfsnqy-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.node
For example, git
Given the tree: 4 / \ 2 7 / \ 1 3 And the value to search: 2
You should return this subtree:github
2 / \ 1 3
In the example above, if we want to search the value 5
, since there is no node with value 5
, we should return NULL
.微信
Note that an empty tree is represented by NULL
, therefore you would see the expected output (serialized tree format) as []
, not null
.this
給定二叉搜索樹(BST)的根節點和一個值。 你須要在BST中找到節點值等於給定值的節點。 返回以該節點爲根的子樹。 若是節點不存在,則返回 NULL。spa
例如,code
給定二叉搜索樹: 4 / \ 2 7 / \ 1 3 和值: 2
你應該返回以下子樹:orm
2 / \ 1 3
在上述示例中,若是要找的值是 5
,但由於沒有節點值爲 5
,咱們應該返回 NULL
。htm
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 }