码迷,mamicode.com
首页 > 其他好文 > 详细

Max Tree

时间:2016-04-29 09:21:46      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

  • The root is the maximum number in the array
  • The left subtree and right subtree are the max trees of the subarray divided by the root number.

Construct the max tree by the given array.

Example

Given [2, 5, 6, 0, 3, 1], the max tree constructed by this array is:

    6
   /   5   3
 /   / 2   0   1

采用递归的解法会Stack Overflow. 因此尝试非递归解法。
先给出递归解法。
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param A: Given an integer array with no duplicates.
15      * @return: The root of max tree.
16      */
17     public TreeNode maxTree(int[] A) {
18         if (A == null || A.length == 0) {
19             return null;
20         }
21         return helper(A, 0, A.length - 1);
22     }
23     
24     private int findMax(int[] A, int left, int right) {
25         int max = Integer.MIN_VALUE;
26         int ans = -1;
27         for (int i = left; i <= right; i++) {
28             if (max < A[i]) {
29                 ans = i;
30                 max = A[i];
31             }
32         }
33         return ans;
34     }
35     
36     private TreeNode helper(int[] A, int left, int right) {
37         if (left > right) {
38             return null;
39         }
40         int position = findMax(A, left, right);
41         TreeNode root = new TreeNode(A[position]);
42         root.left = helper(A, left, position - 1);
43         root.right = helper(A, position + 1, right);
44         return root;
45     }
46 }

 

Max Tree

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5445059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!