lintcode 126.最大树

lintcode

image.png

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param A: Given an integer array with no duplicates.
     * @return: The root of max tree.
     */
    public TreeNode maxTree(int[] A) {
        // write your code here
        if(A == null || A.length == 0){
            return null;
        }
        Stack st = new Stack();
        
        for(int i = 0; i < A.length; i++){
            TreeNode p = new TreeNode(A[i]);
            
            
            if(st.isEmpty() || st.peek().val > p.val){
                st.push(p);
                continue;
            }
            
            TreeNode top = st.pop();
            
            while(!st.isEmpty() && st.peek().val < p.val){
                TreeNode cur = st.pop();
                cur.right = top;
                top = cur;
            }
            p.left = top;
            st.push(p);
        }
        
        TreeNode root = st.pop();
        while(!st.isEmpty()){
            TreeNode cur = st.pop();
            cur.right = root;
            root = cur;
        }
        
        return root;
    }
}

你可能感兴趣的:(lintcode 126.最大树)