Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. 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:

  1. The size of the given array will be in the range [1,1000].

给一个数组,以数组中的最大值为根结点创建一个最大二叉树,分隔出的左右部分再分别创建最大二叉树。

解法:递归

Java:

public class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null) return null;
return build(nums, 0, nums.length - 1);
} private TreeNode build(int[] nums, int start, int end) {
if (start > end) return null; int idxMax = start;
for (int i = start + 1; i <= end; i++) {
if (nums[i] > nums[idxMax]) {
idxMax = i;
}
} TreeNode root = new TreeNode(nums[idxMax]); root.left = build(nums, start, idxMax - 1);
root.right = build(nums, idxMax + 1, end); return root;
}
}

Java:

public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums, 0, nums.length);
} TreeNode construct(int[] nums, int l, int r) {
if (l >= r) return null;
int maxi = l;
for (int i = l + 1; i < r; i++) if (nums[i] > nums[maxi]) maxi = i;
TreeNode root = new TreeNode(nums[maxi]);
root.left = construct(nums, l, maxi);
root.right = construct(nums, maxi + 1, r);
return root;
}  

Python:

def constructMaximumBinaryTree(self, nums):
if not nums:
return None
root, maxi = TreeNode(max(nums)), nums.index(max(nums))
root.left = self.constructMaximumBinaryTree(nums[:maxi])
root.right = self.constructMaximumBinaryTree(nums[maxi + 1:])
return root  

Python:

# Time:  O(n)
# Space: O(n)
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
"""
nodeStack = []
for num in nums:
node = TreeNode(num);
while nodeStack and num > nodeStack[-1].val:
node.left = nodeStack.pop()
if nodeStack:
nodeStack[-1].right = node
nodeStack.append(node)
return nodeStack[0]

Python:

class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return mx = float('-inf')
mx_index = 0
for i in range(len(nums)):
if nums[i] > mx:
mx = nums[i]
mx_index = i root = TreeNode(mx)
if mx_index > 0:
root.left = self.constructMaximumBinaryTree(nums[:mx_index])
if mx_index < len(nums) - 1:
root.right = self.constructMaximumBinaryTree(nums[mx_index+1:]) return root  

C++:

class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.empty()) return NULL;
int mx = INT_MIN, mx_idx = 0;
for (int i = 0; i < nums.size(); ++i) {
if (mx < nums[i]) {
mx = nums[i];
mx_idx = i;
}
}
TreeNode *node = new TreeNode(mx);
vector<int> leftArr = vector<int>(nums.begin(), nums.begin() + mx_idx);
vector<int> rightArr = vector<int>(nums.begin() + mx_idx + 1, nums.end());
node->left = constructMaximumBinaryTree(leftArr);
node->right = constructMaximumBinaryTree(rightArr);
return node;
}
};

C++:  

class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.empty()) return NULL;
return helper(nums, 0, nums.size() - 1);
}
TreeNode* helper(vector<int>& nums, int left, int right) {
if (left > right) return NULL;
int mid = left;
for (int i = left + 1; i <= right; ++i) {
if (nums[i] > nums[mid]) {
mid = i;
}
}
TreeNode *node = new TreeNode(nums[mid]);
node->left = helper(nums, left, mid - 1);
node->right = helper(nums, mid + 1, right);
return node;
}
};

C++:  

class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
vector<TreeNode*> v;
for (int num : nums) {
TreeNode *cur = new TreeNode(num);
while (!v.empty() && v.back()->val < num) {
cur->left = v.back();
v.pop_back();
}
if (!v.empty()) {
v.back()->right = cur;
}
v.push_back(cur);
}
return v.front();
}
};

  

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 654. Maximum Binary Tree 最大二叉树的更多相关文章

  1. LeetCode 654. Maximum Binary Tree最大二叉树 (C++)

    题目: Given an integer array with no duplicates. A maximum tree building on this array is defined as f ...

  2. LeetCode - 654. Maximum Binary Tree

    Given an integer array with no duplicates. A maximum tree building on this array is defined as follo ...

  3. 654. Maximum Binary Tree最大二叉树

    网址:https://leetcode.com/problems/maximum-binary-tree/ 参考: https://leetcode.com/problems/maximum-bina ...

  4. [LeetCode]654. Maximum Binary Tree最大堆二叉树

    每次找到数组中的最大值,然后递归的构建左右树 public TreeNode constructMaximumBinaryTree(int[] nums) { if (nums.length==0) ...

  5. 654. Maximum Binary Tree

    654. Maximum Binary Tree 题目大意: 意思就是给你一组数,先选一个最大的作为根,这个数左边的数组作为左子树,右边的数组作为右子树,重复上一步. 读完就知道是递归了. 这个题真尼 ...

  6. [Leetcode Week14]Maximum Binary Tree

    Maximum Binary Tree 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/maximum-binary-tree/description/ ...

  7. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  8. 【leetcode】654. Maximum Binary Tree

    题目如下: Given an integer array with no duplicates. A maximum tree building on this array is defined as ...

  9. [LeetCode] 655. Print Binary Tree 打印二叉树

    Print a binary tree in an m*n 2D string array following these rules: The row number m should be equa ...

随机推荐

  1. 下载恶意pcap包的网站

    说几个我经常用的,免费的:1.  Malware  Traffic  Analysis:  http://www.malware-traffic-analysis.net/2018/index.htm ...

  2. anyproxy学习1-windows平台安装和抓手机app上https请求

    前言 做接口测试肯定离不开抓包,目前比较流行的抓包工具是fiddler和charles,相信并不陌生.这里介绍一个阿里公司研发的一个抓包神器,只需打开web页面,就能抓到手机app上的http和htt ...

  3. Java.io.tmpdir介绍

    System.getproperty(“java.io.tmpdir”)是获取操作系统缓存的临时目录,不同操作系统的缓存临时目录不一样, 在Windows的缓存目录为:C:\Users\登录用户~1\ ...

  4. Beta:凡事预则立

    课程名称:软件工程1916|W(福州大学) 作业要求:项目Beta冲刺) 团队名称:葫芦娃队 作业目标:尽力完成 团队博客 队员学号 队员昵称 博客地址 041602421 der himmel ht ...

  5. linux 统计某个文件的行数

    今日思语:迷茫的时候,看看身边那些优秀的人,他们还在那么努力,或许你就可以有点方向和动力了 在linux系统中,我们经常会对文件做行数统计,可以使用如下命令 wc -l file #file为具体的文 ...

  6. 导出服务器Oracle数据库为dmp文件

    本文链接:https://blog.csdn.net/rensheng_ruxi/article/details/79877267一.前提:本机安装有Oracle客户端,并且是正确安装. 二.导出Or ...

  7. 正确创建本地C++发布构建PDBS

    在调试版本中遇到的一个问题是编译本地的C++应用程序.例如,许多局部变量消失了,因为代码生成器没有将它们放在堆栈上,而是将它们放在寄存器中,就像在调试生成中发生的那样.此外,release积极地构建对 ...

  8. Linux修改服务器Oracle字符集

    Linux安装Oracle时太仓促,没设置好,导入dmp字符集(ZHS16GBK)与服务器字符集(WE8MSWIN1252)对不上,导致导入数据失败: [oracle@ORACLE ~]$ sqlpl ...

  9. gulp初体验

    项目流程 安装nodejs -> 全局安装gulp -> 项目安装gulp以及gulp插件 -> 配置gulpfile.js -> 运行任务 常用命令简介: node -v 查 ...

  10. uni-app快速上手

    uni-app支持通过 可视化界面.vue-cli命令行 两种方式快速创建项目. 通过 HBuilderX 可视化界面可视化的方式比较简单,HBuilderX内置相关环境,开箱即用,无需配置nodej ...