889. Construct Binary Tree from Preorder and Postorder Traversal

根据前序和后序重建二叉树,不会,哭:),discussion

889. Construct Binary Tree from Preorder and Postorder Traversal

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        if( pre.empty())return NULL;
        stack<TreeNode*> st;
        int l = pre.size();
        TreeNode* root = new TreeNode( pre[ 0 ] );
        st.push( root );
        int ptr = 0;
        for( int i = 1 ; i < l ; i ++ ){
            TreeNode* node = new TreeNode( pre[ i ] );
            if( st.top()->left == NULL )st.top()->left = node;
            else st.top()->right = node;
            st.push( node );
            while( !st.empty() && st.top()->val == post[ ptr ] && ptr < l ){
                st.pop();
                ptr ++;
            }
        }
        return root;
    }
};

应该是一样的思路,感觉上面的思路更清晰一点 

889. Construct Binary Tree from Preorder and Postorder Traversal

 这里他还用到了stack.pop_back() , stack.back() 等函数,但是在stack里面并不常用,于是我查了一下,事实上stack是将底层数据结构封装起来的数据类型,它的底层数据结构是双向队列deque,deque中有这些函数

889. Construct Binary Tree from Preorder and Postorder Traversal

但是使用了这些函数,leetcode并不能编译通过,,,