class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
TreeNode* root = new TreeNode(pre[0]);
vector<TreeNode*> st = {root};
int at = 0;
for (int i = 1; i < pre.size(); i++) {
TreeNode* cur = new TreeNode(pre[i]);
if (st.back()->left == NULL)
st.back()->left = cur;
else
st.back()->right = cur;
st.push_back(cur);
while (!st.empty() && at != post.size() && post[at] == st.back()->val)
at++, st.pop_back();
}
return root;
}
};
这里是在leetcode上找到的代码,这条代码非常有创意!
解读:首先将先序遍历的左孩子不断加入到向量中,并且由向量中的上一个元素指向它
当后序遍历的at值与先序遍历的当前元素值相等时,三种情况:
1.左孩子到了尽头
2.右孩子到了尽头
3.父亲到了尽头
无论上述哪一种情况,最终都是该节点的左右孩子都已构建完毕,该节点可以从vector中剔除。
当vector中所有的元素都剔除了,那么就说明该二叉树的所有节点均已搭建完毕!