根據前序和後序遍歷構造二叉樹(failed)
阿新 • • 發佈:2019-02-04
返回與給定的前序和後序遍歷匹配的任何二叉樹。
pre
和 post
遍歷中的值是不同的正整數。
示例:
輸入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] 輸出:[1,2,3,4,5,6,7]
提示:
1 <= pre.length == post.length <= 30
pre[]
和post[]
都是1, 2, ..., pre.length
的排列- 每個輸入保證至少有一個答案。如果有多個答案,可以返回其中一個。
分析 輸入必然是滿二叉樹
然後就木有然後了
畫個圖
附榜上dalao的AC答案
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; } };