mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #178 from jojoo15/patch-10
添加 0700.二叉搜索树中的搜索 python版本
This commit is contained in:
@ -212,13 +212,18 @@ Python:
|
|||||||
递归法:
|
递归法:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
# Definition for a binary tree node.
|
||||||
|
# class TreeNode:
|
||||||
|
# def __init__(self, val=0, left=None, right=None):
|
||||||
|
# self.val = val
|
||||||
|
# self.left = left
|
||||||
|
# self.right = right
|
||||||
class Solution:
|
class Solution:
|
||||||
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
|
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
|
||||||
if root is None:
|
if not root or root.val == val: return root //为空或者已经找到都是直接返回root,所以合并了
|
||||||
return None
|
if root.val > val: return self.searchBST(root.left,val) //注意一定要加return
|
||||||
if val < root.val: return self.searchBST(root.left, val)
|
else: return self.searchBST(root.right,val)
|
||||||
elif val > root.val: return self.searchBST(root.right, val)
|
|
||||||
else: return root
|
|
||||||
```
|
```
|
||||||
|
|
||||||
迭代法:
|
迭代法:
|
||||||
|
Reference in New Issue
Block a user