lintcode 126.最大樹(shù)

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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言:好久沒(méi)上lintcode了,今天一登,發(fā)現(xiàn)有好多新題。先刷幾十道玩玩。 Palindrome Permuta...
    平_繁閱讀 430評(píng)論 0 0
  • 由于簡(jiǎn)書不支持 Latex ,建議去我的博客看原文:斐波納契數(shù)列實(shí)現(xiàn)及優(yōu)化求關(guān)注、求交流、求意見(jiàn)、求建議。 前言 ...
    華方閱讀 1,968評(píng)論 1 3
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,890評(píng)論 0 33
  • 再這么忙,我就要失去自我了。 我警醒自己,我警告自己,每天至多做兩個(gè)項(xiàng)目的事情,思考兩個(gè)項(xiàng)目的問(wèn)題。國(guó)慶回來(lái),從來(lái)...
    天藍(lán)的新靈閱讀 206評(píng)論 0 0
  • “你有沒(méi)有暗戀過(guò)一個(gè)人,那種酸酸甜甜的感覺(jué),讓人癲狂。像守護(hù)著一個(gè)隱秘的寶藏一樣,只有你知道。偷偷望了很多眼他,又...
    林深時(shí)見(jiàn)鹿X不具名先生閱讀 192評(píng)論 0 1

友情鏈接更多精彩內(nèi)容