654. Maximum Binary Tree

来源:互联网 发布:天龙八部辅助软件 编辑:程序博客网 时间:2024/05/22 15:28

1.题目

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].

2.分析
考察树形结构的题,树形结构本身进行递归定义,所以使用递归就能重建一个树,这里不是标准的树形结构,我们只需要根据题目的要求就可以实现树的自定义与重建。
3.解题
我的解法

class Solution {public TreeNode constructMaximumBinaryTree(int[] nums) {    //边界处理,定义一个root节点    TreeNode root = null;    if(nums==null||nums.length==0){        return root;    }    int maxnumber = Integer.MIN_VALUE;; // 当前数组最大值    int index = 0; // 当前最大值下标    int len = nums.length;    for(int i=0;i<len;i++){        if(nums[i]>=maxnumber){            index = i;            maxnumber = nums[i];        }    }    root = new TreeNode(maxnumber);    int[]left = new int[index];    int[]right = new int[len-index-1];    // 左侧数组初始化    for(int i=0;i<index;i++){        left[i] = nums[i];    }    // 右侧数组初始化    for(int i=index+1;i<len;i++){        right[i-index-1] = nums[i];    }    root.left = constructMaximumBinaryTree(left); // 递归左子树    root.right = constructMaximumBinaryTree(right); // 递归右子树    return root;}}

4.总结
看了别人的解法,大同小异,都是采用的递归,只是中间有很多可以优化的地方,我中间使用了不少辅助空间来保存中间结果,别人的解法中没有使用辅助空间,这样空间开销就小很多。

原创粉丝点击