标签:
Question:
Given an integer array with no duplicates. A max tree building on this array is defined as follow:
Construct the max tree by the given array.
Given [2, 5, 6, 0, 3, 1]
, the max tree constructed by this array is:
6
/ 5 3
/ / 2 0 1
Analysis:
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 int size = A.length; 19 if(A == null || size == 0) { 20 return null; 21 } 22 23 Stack<TreeNode> stack = new Stack<TreeNode>(); 24 for(int i = 0; i <= size; i++) { 25 TreeNode right = i == size ? new TreeNode(Integer.MAX_VALUE) 26 : new TreeNode(A[i]); 27 28 while(!stack.isEmpty() && right.val > stack.peek().val) { 29 TreeNode node = stack.pop(); 30 if(stack.isEmpty()) { 31 right.left = node; 32 }else { 33 TreeNode left = stack.peek(); 34 if(left.val > right.val) { 35 right.left = node; 36 }else { 37 left.right = node; 38 } 39 } 40 } 41 42 stack.push(right); 43 } 44 45 return stack.peek().left; 46 } 47 }
标签:
原文地址:http://www.cnblogs.com/billzhou0223/p/5151399.html