博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
700. Search in a Binary Search Tree
阅读量:4988 次
发布时间:2019-06-12

本文共 1390 字,大约阅读时间需要 4 分钟。

1. Quesiton

700. Search in a Binary Search Tree

url: https://leetcode.com/problems/search-in-a-binary-search-tree/description/

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, 

Given the tree:        4       / \      2   7     / \    1   3And 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.


 
 
2. Solution:
# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = None        class Solution(object):    def searchBST(self, root, val):        """        :type root: TreeNode        :type val: int        :rtype: TreeNode        """        if root is None:            return []        if root.val == val:            return root        if root.val < val:            return self.searchBST(root.right, val)        else:            return self.searchBST(root.left, val)

 

转载于:https://www.cnblogs.com/ordili/p/9976043.html

你可能感兴趣的文章
0x51 线性DP
查看>>
mongo数据库的增删改查
查看>>
软件工程驻足篇章:第十七周和BugPhobia团队漫长的道别
查看>>
ideal 快捷键
查看>>
python
查看>>
DedeCms常用内容调用标签实例大全
查看>>
使用soapui调用webservice接口
查看>>
java 线程协作 join()
查看>>
golang学习笔记15 golang用strings.Split切割字符串
查看>>
jQuery页面滚动图片等元素动态加载实现
查看>>
深入理解对象的引用
查看>>
starUML破解-version2.8.0已验证
查看>>
selenium实战学习第一课
查看>>
马后炮之12306抢票工具(三) -- 查票(监控)
查看>>
198. House Robber Java Solutions
查看>>
Java_基础篇(杨辉三角)
查看>>
__str__ __repr__ 与 __format__
查看>>
【LoadRunner】loadrunner常见问题汇总
查看>>
css 不换行省略号
查看>>
BZOJ4001 TJOI2015概率论(生成函数+卡特兰数)
查看>>