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

        

 

转载于:https://www.cnblogs.com/yao1996/p/10341297.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值