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<TreeNode> st = new Stack<TreeNode>();
        
        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了,今天一登,发现有好多新题。先刷几十道玩玩。 Palindrome Permuta...
    平_繁阅读 409评论 0 0
  • 由于简书不支持 Latex ,建议去我的博客看原文:斐波纳契数列实现及优化求关注、求交流、求意见、求建议。 前言 ...
    華方阅读 1,907评论 1 3
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 再这么忙,我就要失去自我了。 我警醒自己,我警告自己,每天至多做两个项目的事情,思考两个项目的问题。国庆回来,从来...
    天蓝的新灵阅读 175评论 0 0
  • “你有没有暗恋过一个人,那种酸酸甜甜的感觉,让人癫狂。像守护着一个隐秘的宝藏一样,只有你知道。偷偷望了很多眼他,又...
    林深时见鹿X不具名先生阅读 161评论 0 1