/**
* 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 {
TreeNode result = null;
public TreeNode searchBST(TreeNode root, int val) {
inorder(root, val);
return result;
}
public void inorder(TreeNode node, int target) {
if(node != null) {
inorder(node.left, target);
if(node.val == target) {
result = node;
}
inorder(node.right, target);
}
}
}
/**
* 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) {
TreeNode result = null;
if(root.val == val) {
return root;
}
if(root.val > val && root.left != null) {
result = searchBST(root.left, val);
}else if (root.val < val && root.right != null){
result = searchBST(root.right, val);
}
return result;
}
}
'JAVA > leetcode' 카테고리의 다른 글
[LeetCode Medium] BST - Delete Node in a BST !! (0) | 2021.08.10 |
---|---|
[LeetCode Medium] BST - Insert into a Binary Search Tree (0) | 2021.08.10 |
[LeetCode Medium] BST - Binary Search Tree Iterator (0) | 2021.08.10 |
[LeetCode Medium] BST - Validate Binary Search Tree !! (0) | 2021.08.10 |
[LeetCode] Two Sum II - Two Pointer (0) | 2021.08.09 |