LeetCode 700. Search in a Binary Search Tree

一、题目

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,
LeetCode 700. Search in a Binary Search Tree_第1张图片

二、代码实现

/**
 * 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 || root.val == val)
            return root;
        else if(val < root.val)
            return searchBST(root.left, val);
        else 
            return searchBST(root.right, val);
    }
}

你可能感兴趣的:(#,LeetCode)