Title description:
Given the root node of the binary search tree (BST) and a value. You need to find a node in the BST that has a node value equal to a given value. Returns the subtree rooted at this node. If the node does not exist, NULL is returned.
For example,
given a binary search tree:
4
/ \
2 7
/ \
1 3
Sum value: 2
You should return the following subtree:
2
/ \
1 3
In the above example, if the value we are looking for is 5, but because there is no node with a value of 5, we should return NULL.
code show as below:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while (root != null && val != root.val)
root = val < root.val ? root.left : root.right;
return root;
}
}
Results of the: