0%

June Leetcoding Challenge(6.15)

LeetCode六月挑战(6.15) Search in a Binary Search Tree LeetCode700 解题报告

今天的题目比较简单
Search in a Binary Search Tree

Solution
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
For example, 

Given the tree:
4
/ \
2 7
/ \
1 3

And the value to search: 2
You should return this subtree:

2
/ \
1 3
In the example above, if we want to search the value 5, since there is no node with value 5, we should return 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直接返回NULL,然后比较根节点的值,如果相等就直接返回root,如果不相等,如果小于根节点,则递归searchBST左子树,如果大于根节点,则递归searchBST右子树。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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 || val == root.val )
return root;
if(val > root.val)
return searchBST(root.right,val);
return searchBST(root.left,val);
}
}
-------------本文结束感谢您的阅读-------------

本文标题:June Leetcoding Challenge(6.15)

文章作者:Jungle

发布时间:2020年06月15日 - 08:35

最后更新:2020年06月15日 - 08:41

原始链接:http://yoursite.com/2020/06/15/LeetCodeJuneChallenge15th/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Welcome to my other publishing channels