首页 > 其他 > 详细

LeetCode 700 Search in a Binary Search Tree 解题报告

时间:2019-01-31 12:01:33      阅读:143      评论:0      收藏:0      [点我收藏+]

题目要求

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 解题报告

原文:https://www.cnblogs.com/yao1996/p/10341297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!