Leetcode 700. Search in a Binary Search Tree(递归)

Leetcode 700. Search in a Binary Search Tree

题目链接: Search in a Binary Search Tree

难度:Easy

题目大意:

在二分搜索树(BST)中查找值为val的节点,返回以该节点为根节点的二叉树,如果找不到则返回null。

思路:

递归,先对根节点进行判断,然后对其子节点进行相同的操作。

代码

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

你可能感兴趣的:(Leetcode,leetcode,二叉树)