时间:2020-9-21
题目地址:https://leetcode-cn.com/problems/search-in-a-binary-search-tree/
题目难度:Easy
题目描述:
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
例如,
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和值: 2
你应该返回如下子树:
2
/ \
1 3
在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。
思路1:递归
根据BST的特性,对于每个节点:
如果目标值等于节点的值,则返回节点;
如果目标值小于节点的值,则继续在左子树中搜索;
如果目标值大于节点的值,则继续在右子树中搜索。
代码段1:通过
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if root:
if root.val > val:
return self.searchBST(root.left, val)
elif root.val < val:
return self.searchBST(root.right, val)
else:
return root
else:
return None
总结:
-
递归的return 理解不了,刚开始大于小于的时候没有return,一直没有结果.【2021-01-30】现在我写的还是有这种问题。还是不能跳到递归里去,你的脑袋放不下几个递归的,想清楚每个结点要干啥就好。要不返回根节点,要不返回左子树的某一结点,要不返回右子树的某一结点。
-
返回节点,后续自动遍历子树 么?。【2021-01-30】当然咯,返回一个结点,它是有值、左、右的这种数据结构的。
思路2:直接判断
代码段2:通过
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
while root:
if root.val > val:
root = root.left
elif root.val < val:
root = root.right
else:
return root
return None
总结:
-
这也行,时空分别是 n,1
思路3:迭代
代码段3:通过
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
stack = [root]
while stack:
temp = stack.pop()
if temp == None:
continue
if temp.val == val:
return temp
else:
stack.append(temp.left)
stack.append(temp.right)
return None
总结:
-
迭代这个我是真的想不出来了。【2021-01-30】这个相当于就是数的遍历了