Skip to content

Commit 507135e

Browse files
authored
Update 0654.最大二叉树.md
added python version of code
1 parent c4bfb1f commit 507135e

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

problems/0654.最大二叉树.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,25 @@ class Solution {
256256
```
257257

258258
Python:
259-
259+
```python
260+
# Definition for a binary tree node.
261+
# class TreeNode:
262+
# def __init__(self, val=0, left=None, right=None):
263+
# self.val = val
264+
# self.left = left
265+
# self.right = right
266+
//递归法
267+
class Solution:
268+
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
269+
if not nums: return None //终止条件
270+
root = TreeNode(max(nums)) //新建节点
271+
p = nums.index(root.val) //找到最大值位置
272+
if p > 0: //保证有左子树
273+
root.left = self.constructMaximumBinaryTree(nums[:p]) //递归
274+
if p < len(nums): //保证有右子树
275+
root.right = self.constructMaximumBinaryTree(nums[p+1:]) //递归
276+
return root
277+
```
260278

261279
Go:
262280

@@ -267,4 +285,4 @@ Go:
267285
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
268286
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
269287
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
270-
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
288+
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

0 commit comments

Comments
 (0)