解题思路

其实只要知道了二叉搜索树(binary search tree)的性质就会解这道题啦,剩下都是敲代码

  • 若它的左子树不为空,则左子树上所有节点的值均小于它根节点的值
  • 若它的右子树不为空,则右子树上所有节点的值均小于它根节点的值
  • 它的左、右子树也分别为二叉搜索树

代码

Go

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
return binarySearchTree(root, val)
}

func binarySearchTree(root *TreeNode, val int) *TreeNode {
if root == nil || root.Val == val {return root}
if root.Val > val {return binarySearchTree(root.Left, val)}
if root.Val < val {return binarySearchTree(root.Right, val)}
return nil
}

迭代

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func searchBST(root *TreeNode, val int) *TreeNode {
    for root != nil{
        if root.Val > val {
            root = root.Left
        } else if root.Val < val {
            root = root.Right
        } else {
            return root
        }
    }
    return root
}