您的位置:首页 > 其它

【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 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: