二叉搜索树中的搜索 (Search in a Binary Search Tree)

 

思路:

// @Title: 二叉搜索树中的搜索 (Search in a Binary Search Tree)
// @Author: qisiii
// @Date: 2024-09-16 00:59:10
// @Runtime: 0 ms
// @Memory: 44.1 MB
// @comment: 
// @flag: 
/**
 * 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) {
        if(root==null){
            return null;
        }
        if(root.val==val){
            return root;
        }else if(root.val>val){
            return searchBST(root.left,val);
        }else{
             return searchBST(root.right,val);
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18