LeetCode 700 Search in a Binary Search Tree 解题报告
Posted yao1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 700 Search in a Binary Search Tree 解题报告相关的知识,希望对你有一定的参考价值。
题目要求
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.
题目分析及思路
题目给出一棵二叉树和一个数值,要求找到与该数值相等的结点并返回以该结点为根结点的子树。可以使用队列保存结点,再将结点循环弹出进行判断。
python代码?
# 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, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
q = collections.deque()
q.append(root)
while q:
node = q.popleft()
if not node:
continue
if node.val != val:
q.append(node.left)
q.append(node.right)
continue
else:
return node
return None
以上是关于LeetCode 700 Search in a Binary Search Tree 解题报告的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 700 Search in a Binary Search Tree 解题报告
700. Search in a Binary Search Tree
700. Search in a Binary Search Tree