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

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10341297.html