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.
Example
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to search: 2
You should return this subtree:
2
/ \
1 3
입력으로 들어는 val을 루트로 하는 하위트리를 return하는 문제이다. 현재 루트 노드의 값이 val과 같으면 return하고 같지 않으면 자식노드들을 탐색하게 하는데 left부터 조사하고 right를 조사하는 깊이우선 탐색을 사용해서 코드를 작성한다.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var searchBST = function(root, val) {
// val를 루트로 하는 하위트리를 return
// 현재 루트 노드의 값이 val과 같으면 return
// 같지 않으면 자식노드들을 탐색
let binaryTree = null;
let findTree = (curnode) =>{
if(curnode === null){
return ;
}
if(curnode.val === val){
binaryTree = curnode;
return ;
}
findTree(curnode.left);
findTree(curnode.right);
}
findTree(root);
return binaryTree;
};