今天是2019年7月3日,黄哥早起刷了一道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.
这个明显是一个递归问题,那么就用递归去解决。
解题思路:
1、先写一个函数求数组的最大值和它的索引。
2、递归调用数组最大值左边和右边部分。
黄哥写了Go 代码和Java 代码,希望有兴趣的朋友,用Python 去实现。
Go 语言代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 黄哥Python培训 黄哥所写
func constructMaximumBinaryTree(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
maxVal, index := findMaxValue(nums)
root := &TreeNode{
Val: maxVal,
}
root.Left = constructMaximumBinaryTree(nums[:index])
root.Right = constructMaximumBinaryTree(nums[index+1:])
return root
}
func findMaxValue(nums []int) (int, int) {
var max, index int
max = nums[0]
index = 0
for i, val := range nums {
if val > max {
max = val
index = i
}
}
return max, index
}Java 代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 黄哥Python培训 黄哥所写
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums.length == 0 ) {
return null;
}
int[] maxAndIndex = findMaxVal(nums);
int max = maxAndIndex[0];
int index = maxAndIndex[1];
TreeNode root = new TreeNode(max);
root.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, index));
root.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, index+1, nums.length));
return root;
}
public int[] findMaxVal(int[] nums) {
int max, index, i;
int[] res = {0, 0};
max = nums[0];
i = 0;
index = 0;
for (int val: nums) {
if (val > max) {
max = val;
index = i;
}
i += 1;
}
res[0]= max;
res[1] = index;
return res;
}
}