网站做的不好会有什么后果,梧州网站推广费用,网站设计服务费一般多少钱,js 访问网站统计刷新不增加次数Problem: 654. 最大二叉树 文章目录 题目描述思路复杂度Code 题目描述 思路
对于构造二叉树这类问题一般都是利用先、中、后序遍历#xff0c;再将原始问题分解得出结果 1.定义递归函数build#xff0c;每次将一个数组中的最大值作为当前子树的根节点构造二叉树#xff1b;… Problem: 654. 最大二叉树 文章目录 题目描述思路复杂度Code 题目描述 思路
对于构造二叉树这类问题一般都是利用先、中、后序遍历再将原始问题分解得出结果 1.定义递归函数build每次将一个数组中的最大值作为当前子树的根节点构造二叉树 2.每次找取当前范围内的最大值作为当前的根节点 3.递归求取出其左子树与右子树 复杂度
时间复杂度: O ( n 2 ) O(n^2) O(n2)其中n为二叉树节点的个数 空间复杂度: O ( n ) O(n) O(n) Code
/*** Definition for a binary tree node.* public 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;* }* }*/
class Solution {/*** Maximum Binary Tree** param nums Given array* return TreeNode*/public TreeNode constructMaximumBinaryTree(int[] nums) {return build(nums, 0, nums.length - 1);}/*** Construction of binary tree function implementation** param nums Given array* param low Given the left endpoint of the array* param high Given the right endpoint of the array* return TreeNode*/TreeNode build(int[] nums, int low, int high) {if (low high) {return null;}int index -1;int maxVal Integer.MIN_VALUE;for (int i low; i high; i) {if (maxVal nums[i]) {maxVal nums[i];index i;}}//The root node is constructed first,// and then the left and right subtrees are constructedTreeNode root new TreeNode(maxVal);root.left build(nums, low, index - 1);root.right build(nums, index 1, high);return root;}
}