力扣 1008 前序遍歷構(gòu)造二叉搜索樹

題意:給定一個二叉搜索樹的現(xiàn)需遍歷,重構(gòu)二叉搜索樹

思路:先跟遍歷數(shù)組,每次查看當(dāng)前遍歷到的節(jié)點是否在max和min之內(nèi),如果不在,返回null,如果在,取當(dāng)前節(jié)點為root,找到其左右子樹,返回但前節(jié)點

思想:樹的先跟遍歷

復(fù)雜度:時間O(n),空間O(n)

class Solution {
    public TreeNode bstFromPreorder(int[] preorder) {
        int len = preorder.length;
        if(len == 0)
            return null;
        return build(preorder, Integer.MAX_VALUE, Integer.MIN_VALUE);
    }
    int index = 0;
    TreeNode build(int[] preorder, int max, int min) {
        if(index == preorder.length)
            return null;
        int temp = preorder[index];
        if(temp > max || temp < min)
            return null;
        TreeNode cur = new TreeNode(preorder[index++]);
        cur.left = build(preorder, temp, min);
        cur.right = build(preorder, max, temp);
        return cur;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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