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);
}
本文介绍了一种在二叉搜索树(BST)中查找特定值的方法。通过递归遍历,利用BST特性比较节点值与目标值大小,最终找到目标节点或返回NULL。示例展示了如何查找并返回包含目标值的子树。
694

被折叠的 条评论
为什么被折叠?



