leetcode 700. Search in a Binary Search Tree(二叉搜尋樹查詢)
阿新 • • 發佈:2020-12-22
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);
}