[LeetCode] 700. Search in a Binary Search Tree

45 篇文章 0 订阅
14 篇文章 0 订阅

原题链接: https://leetcode.com/problems/search-in-a-binary-search-tree/

1. 题目介绍

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.

给出一个二叉树的根节点和一个value值。你需要在所有二叉树的节点中找到那个val等于value值的节点。返回以这个节点为根节点的子树。如果没有节点等于value,那么返回null

举例:
在这里插入图片描述
应该返回这个子树:
在这里插入图片描述
In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.
在上述的例子中,如果value值等于5,那么这里就没有等于5的节点了。我们应该返回null。

Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
一个空树也可以用NULL表示,因此期望输出的结果应该是[],不是null
(其实我不太懂这句话表达的意思是什么,如果有读者知道,欢迎留言告诉我)

2. 解题思路

这道题是一道遍历树的问题。我们需要遍历这棵树,寻找和value值相等的节点。遍历一棵树有很多种办法,其中深度优先搜索是最适合本题的。根据二叉树的性质,这个根节点左子树里面的所有节点都小于根节点,所有右子树里面的节点都大于根节点。如果使用深度优先搜索的话,假如root.val 的值大于value,那么我们可以直接放弃root的右子树,把搜寻范围确定在左子树上,直接降低了一半的搜索工作量。

具体实现仍然采用深度优先搜索+递归的实现方法。

/**
 * 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;
        }
        
        if(root.val > val){
            return searchBST(root.left,  val);
        }
        if(root.val < val){
            return searchBST(root.right, val);
        }
        
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值