654. Maximum Binary Tree

分類:medium 樹  分治

 

題目介紹

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. 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:

  1. The size of the given array will be in the range [1,1000].

題目翻譯

     給你一個無序的整數數組,你返回一個最大的樹,

1.數組中的最大值爲根節點

2.以根節點爲準,左子樹的根節點爲數組左半部分的最大值

3.以根節點爲準,右子樹的根節點爲數組右半部分的最大值

重複以上步驟,構建二叉樹,最終返回二叉樹的根節點。

 

已給代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

 

解題代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
 	public TreeNode constructMaximumBinaryTree(int[] nums) {
		return getMax(0,nums.length-1,nums);
		}

		public TreeNode getMax(int start,int end,int []nums){
			if(start>end) //結束條件很重要
				return null;
			int temp=nums[start];
			int index=start;
			for(int i=start+1;i<=end;i++){
				if(nums[i]>temp){
					temp=nums[i];
					index=i;
				}
			}
			TreeNode node=new TreeNode(temp);
	        node.left=getMax(start,index-1,nums);//分治法 對左孩子進行遞歸
			node.right=getMax(index+1,end,nums);//    對右孩子進行遞歸
			return node;
		}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章