码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:bin   二叉树   etc   code   相等   sub   leetcode   find   return   

题目要求

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

标签:bin   二叉树   etc   code   相等   sub   leetcode   find   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!