根据两个traversal恢复二叉树

已知前序和中序遍历:

递归版本:

TreeNode* buildTree(vector& preorder, vector& inorder) {
        int len = preorder.size();
        return buildCore(preorder, 0, inorder, 0, len);
    }
    TreeNode* buildCore(vector& preorder, int start1, vector& inorder, int start2, int num) {
        if(num == 0) return NULL;
        TreeNode* root = new TreeNode(preorder[start1]);
        if(num == 1) return root;
        int leftnum = 0, i = start2;
        //find in the inorder
        for(; i left = buildCore(preorder, start1 + 1, inorder, start2, leftnum);
        root -> right = buildCore(preorder, start1 + leftnum + 1, inorder, i + 1, num - leftnum - 1);
        return root;
    }

非递归版本:

TreeNode* buildTree(vector& preorder, vector& inorder) {
        int num = preorder.size();
        if(num == 0) return NULL;
        stack st;
        TreeNode* root = new TreeNode(preorder[0]), *cur = root;
        for(int i = 1, j = 0; i val){
                j++;
                while(!st.empty() && st.top() -> val == inorder[j]){
                    cur = st.top();
                    st.pop();
                    j++;
                }
                cur -> right = new TreeNode(preorder[i]);
                cur = cur -> right;
            }
            else{
                cur -> left = new TreeNode(preorder[i]);
                st.push(cur);
                cur = cur -> left;
            }
        }
        return root;
    }

已知后序和中序遍历:
非递归:

TreeNode* buildTree(vector& inorder, vector& postorder) {
        int len = inorder.size();
        if(len == 0) return NULL;
        stack st;
        TreeNode* root = new TreeNode(postorder[len-1]), *cur = root;
        st.push(root);
        for(int i = len-2, j = len-1; i>=0; i--){
            if(cur -> val != inorder[j]){
                cur -> right = new TreeNode(postorder[i]);
                st.push(cur);
                cur = cur -> right;
            }
            else{
                j--;
                while(!st.empty() && st.top() -> val == inorder[j]){
                    cur = st.top();
                    st.pop();
                    j--;
                }
                cur -> left = new TreeNode(postorder[i]);
                cur = cur -> left;
            }
        }
        return root;
    }

你可能感兴趣的:(根据两个traversal恢复二叉树)