【LeetCode】654. Maximum Binary Tree 解题报告
2018-02-05 22:03
417 查看
【LeetCode】654. Maximum Binary Tree 解题报告
标签: LeetCode题目地址:https://leetcode.com/problems/maximum-binary-tree/description/
题目描述:
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6 / \
3 5
\ /
2 0
\
1
Note:
The size of the given array will be in the range [1,1000].
解题方法
方法一:题意是要根据最大值分割进行构建二叉树。明显的递归的题目。找到数组中的最大值和最大值的位置,然后用切片的方式进行构建。如果数组为空,那么叶子为空。
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None _max = max(nums) max_pos = nums.index(_max) root = TreeNode(_max) root.left = self.constructMaximumBinaryTree(nums[:max_pos]) root.right = self.constructMaximumBinaryTree(nums[max_pos + 1:]) return root
日期
2018 年 2 月 5 日相关文章推荐
- 【LeetCode】144 . Binary Tree Preorder Traversal 解题报告
- [leetcode] 104. Maximum Depth of Binary Tree 解题报告
- LeetCode-Binary Search Tree Iterator-解题报告
- 【LeetCode】Find Bottom Left Tree Value 解题报告
- LeetCode: Binary Tree Level Order Traversal 解题报告
- 【LeetCode】Minimum Depth of Binary Tree 解题报告
- [leetcode] 173. Binary Search Tree Iterator 解题报告
- 【LeetCode】226.Invert Binary Tree(Easy)解题报告
- LeetCode解题报告 100. Same Tree [easy]
- 景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
- LeetCode Convert Sorted List to Binary Search Tree 解题报告
- LeetCode(110) Balanced Binary Tree解题报告
- [LeetCode]Implement Trie(Prefix Tree),解题报告
- 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- Leetcode 100. Same Tree 验证树是否相同 解题报告
- 【LeetCode】208. Implement Trie (Prefix Tree) 解题报告(Python)
- 【LeetCode】Find Largest Value in Each Tree Row 解题报告
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 先序和中序中恢复二叉树 解题报告
- 【LeetCode】Flatten Binary Tree to Linked List 解题报告
- [Leetcode] 100. Same Tree 解题报告