1. 程式人生 > >LeetCode 700 Search in a Binary Search Tree 解題報告

LeetCode 700 Search in a Binary Search Tree 解題報告

lec 一個 earch 結點 返回 要求 hat none 一個數

題目要求

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 解題報告