Q:
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
例如,
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和值: 2
你应该返回如下子树:
2
/ \
1 3
在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。
链接:https://leetcode-cn.com/problems/search-in-a-binary-search-tree/description/
思路:利用二叉树的前序遍历,如果遍历到的节点的值与给定值相等,则返回子树
代码:
# 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
"""
result, stack = 0, [root]
while stack:
node = stack.pop()
if node:
if val == node.val:
return node
if node.val < val:
stack.append(node.right)
if val < node.val:
stack.append(node.left)
return None

本文介绍了一种在二叉搜索树(BST)中查找指定值节点并返回其子树的方法。通过前序遍历,当遍历到的节点值与给定值相等时,返回该节点作为子树的根。若未找到对应值,则返回NULL。
417

被折叠的 条评论
为什么被折叠?



