LeetCode From Easy To Hard No9 [easy]: Search in a Binary Search Tree 두 갈래 나무의 값 찾기
1425 단어 LeetCode
For example,
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to search: 2
You should return this subtree:
2
/ \
1 3
In the example above, if we want to search the value
5
, since there is no node with value 5
, we should return NULL
. Note that an empty tree is represented by
NULL
, therefore you would see the expected output (serialized tree format) as []
, not null
. 두 갈래 트리의 값을 찾은 다음 이 값을 루트로 하는 하위 트리로 돌아갑니다.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
if (root.val == val) {
return root;
} else {
// , , ,
return root.val > val ? searchBST(root.left, val) : searchBST(root.right, val);
}
}
}