Merge pull request #166 from jojoo15/patch-8

添加 0654.最大二叉树 python版本
This commit is contained in:
Carl Sun
2021-05-18 15:21:52 +08:00
committed by GitHub

View File

@ -256,7 +256,25 @@ class Solution {
```
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:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums: return None //终止条件
root = TreeNode(max(nums)) //新建节点
p = nums.index(root.val) //找到最大值位置
if p > 0: //保证有左子树
root.left = self.constructMaximumBinaryTree(nums[:p]) //递归
if p < len(nums): //保证有右子树
root.right = self.constructMaximumBinaryTree(nums[p+1:]) //递归
return root
```
Go
@ -267,4 +285,4 @@ Go
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频[代码随想录](https://space.bilibili.com/525438321)
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>