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 constructed
TreeNode root = new TreeNode(maxVal);
root.left = build(nums, low, index - 1);
root.right = build(nums, index + 1, high);
return root;
}
}