[LeetCode] 654. Maximum Binary Tree 最大二叉树
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].
给一个数组,以数组中的最大值为根结点创建一个最大二叉树,分隔出的左右部分再分别创建最大二叉树。
解法:递归
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 最大二叉树的更多相关文章
- LeetCode 654. Maximum Binary Tree最大二叉树 (C++)
题目: Given an integer array with no duplicates. A maximum tree building on this array is defined as f ...
- LeetCode - 654. Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follo ...
- 654. Maximum Binary Tree最大二叉树
网址:https://leetcode.com/problems/maximum-binary-tree/ 参考: https://leetcode.com/problems/maximum-bina ...
- [LeetCode]654. Maximum Binary Tree最大堆二叉树
每次找到数组中的最大值,然后递归的构建左右树 public TreeNode constructMaximumBinaryTree(int[] nums) { if (nums.length==0) ...
- 654. Maximum Binary Tree
654. Maximum Binary Tree 题目大意: 意思就是给你一组数,先选一个最大的作为根,这个数左边的数组作为左子树,右边的数组作为右子树,重复上一步. 读完就知道是递归了. 这个题真尼 ...
- [Leetcode Week14]Maximum Binary Tree
Maximum Binary Tree 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/maximum-binary-tree/description/ ...
- 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...
- 【leetcode】654. Maximum Binary Tree
题目如下: Given an integer array with no duplicates. A maximum tree building on this array is defined as ...
- [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 ...
随机推荐
- js 变量以及函数传参
一.变量: 基本类型是变量对象重新创建一个新值给变量对象空间,虽然是同一个值但是互不影响. 引用类型是也是将一个值重新赋值给新的变量空间,但是这个值是堆中对象的一个指针,新的变量和旧的变量指向是同一个 ...
- 快排算法Java版-每次以最左边的值为基准值手写QuickSort
如题 手写一份快排算法. 注意, 两边双向找值的时候, 先从最右边起找严格小于基准值的值,再从最左边查找严格大于基准base的值; 并且先右后左的顺序不能反!!这个bug改了好久,233~ https ...
- django--学习笔记 一
django--学习笔记 一 简介 本次笔记来源于对django官方教程的学习总结,点击进入官方教程. 要点 1.django框架简单介绍: 2.如何创建项目,创建项目介绍: 3.如何在项目在创建应用 ...
- charAt,charCode,fromCharCode区别
1.charAt 返回字符串指定位置的字符 2.charCode 返回字符串指定位置字符Unicode编码 3.fromCharCode 用Unicode编码创建字符串 我们来看下例子 var str ...
- js中的全局对象
- cookie插件|jq-cookie.js|使用详解
1.设置一二级域名共用的cookie:设置domain为一级域名,可一.二级域名共用的cookie $.cookie('f_city','北京|101010100|,锦州|101070701|',{e ...
- Top 20 IoT Platforms in 2018
https://internetofthingswiki.com/top-20-iot-platforms/634/ After learning what is the internet of th ...
- Cocos2d-x学习小结 配置篇
Cocos2d-x学习小结 配置篇 学习工具:Cocos2d-x用户手册,<Cocos2d-x游戏开发之旅> 首先官网下载cocos2d-x源码,安装vs2019.如果没有安装python ...
- 认识Nodejs
一.概念 ①JavaScript运行环境:Node.js不是一门语言,不是库也不是框架,是一个JavaScript运行环境,简单点来讲就是Node.js可以解析执行JavaScript代码,也就是说J ...
- gulp+apache代理请求处理javascript跨域请求
apache设置(参考) 用 apache 的 mod_proxy 模块开启反向代理功能来实现: 1 修改 apache 配置文件 httpd.conf ,去掉以下两行前面 # 号 LoadModul ...