Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0 Star 0 Fork 0

徐云天/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
_654.java 2.35 KB
一键复制 编辑 原始数据 按行查看 历史
徐云天 提交于 2021-06-10 10:00 +08:00 . 删除无用的导入包
/**
* 原题 : https://leetcode.com/problems/maximum-binary-tree/
* 1. 递归 2.stack (暂时没明白)
*/
public class _654 {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
static class Solution1 {
//递归解法时间复杂度 O(N*lgN)
public TreeNode constructMaximumBinaryTree(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
public TreeNode helper(int[] nums, int i, int j) {
if (i > j) return null;
TreeNode cur = new TreeNode();
int maxIdx = findMAX(nums, i, j);
cur.val = nums[maxIdx];
cur.left = helper(nums, i, maxIdx - 1);
cur.right = helper(nums, maxIdx + 1, j);
return cur;
}
public int findMAX(int[] nums, int l, int r) {
//暴力搜索
int max = l;
for (int i = l + 1; i <= r; i++) {
if (nums[i] > nums[max]) {
max = i;
}
}
return max;
}
}
static class Solution2 {
public TreeNode constructMaximumBinaryTree(int[] nums) {
//stack思路,可以理解为不断将值插入该树
//当前元素的左节点为栈中最后一个小于当前值的节点,
//栈中存在元素一定大于当前节点
//栈顶元素的右节点一定为它右边的最大值,随着插入的数据变化
TreeNode[] stack = new TreeNode[nums.length];
int p = -1;
for (int val : nums) {
TreeNode cur = new TreeNode(val);
while (p >= 0 && stack[p].val < cur.val) {
cur.left = stack[p--];
}
if (p >= 0) {
stack[p].right = cur;
}
stack[++p] = cur;
}
return p >= 0 ? stack[0] : null;
}
}
public static void main(String[] args) {
int[] nums = {7, 1, 4, 5, 9, 8, 2, 18, 45, 23};
new Solution2().constructMaximumBinaryTree(nums);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuyuntian/leetcode.git
git@gitee.com:xuyuntian/leetcode.git
xuyuntian
leetcode
leetcode
master