leetcode 1028從先序遍歷還原二叉樹 迭代寫法

public TreeNode recoverFromPreorder(String S) {
    //利用棧來保存結點, 新遍歷到的結點肯定是某一子節點(根結點除外),由於是先序遍歷
    //那麼可能是上一個遍歷結點的左孩子,要麼是之前的已經遍歷的右孩子
    LinkedList<TreeNode> stack = new LinkedList<>();
    int pos = 0;
    while(pos<S.length()){
        //首先拿到深度信息
        int depth = 0;
        while(pos<S.length() && S.charAt(pos) == '-'){
            depth++;
            pos++;
        }
        //再拿到結點信息
        int value = 0;
        while(pos<S.length() && S.charAt(pos) != '-'){
            value = value*10 + S.charAt(pos) - '0';
            pos++;
        }
        TreeNode node = new TreeNode(value);
        if(depth == stack.size()){
           if(!stack.isEmpty()){
                stack.peek().left = node;
           }
        }else{//此時說明棧頂節點不是其父結點應該棧頂節點一直出棧 utill 滿足條件
        //用迭代模擬回溯
            while(stack.size() != depth){
                stack.pop();
            }
            stack.peek().right = node;
        }
        stack.push(node);

    }
    TreeNode root = null;
    while(!stack.isEmpty()){
        root = stack.pop();
    }
    return root;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章