leetcode 700. Search in a Binary Search Tree(二叉搜索树查找)

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

查找二叉搜索树中的值,如果值不存在,返回NULL

思路:
根据BST左子树值< root.val < 右子树值 的特点

    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null) return null;
        if(root.val == val) return root;
        if(root.val > val) return searchBST(root.left, val);
        return searchBST(root.right, val);
    }

你可能感兴趣的:(leetcode,leetcode)