Problem
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre
and post
are distinct positive integers.
Example
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Answer
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
stack<TreeNode*> s;
s.push(new TreeNode(pre[0]));
for (int i = 1, j = 0; i < pre.size(); ++i) {
TreeNode* node = new TreeNode(pre[i]);
while(s.top()->val == post[j]) {
s.pop();
j++;
}
if (!s.top()->left) s.top()->left = node;
else s.top()->right = node;
s.push(node);
}
return s.top();
}
Explanation
感觉这题其实不是太好理解。
首先要对前序遍历和后续遍历比较熟悉
Preorder (Root, Left, Right) 4 2 5 1 3
Postorder (Left, Right, Root) 4 5 2 3 1
如果只给pre
是无法完成建树的,因为不知道某个节点是否是最底部的点。所以post
给了一个很重要的信息。
首先维护一个stack
,里面存放还没完成建数的node
,同时维护一个指针j
,来检查stack
里面的node
是否完成建树。
- 遍历
pre
,每一个数字都取出来建立新的node
- 取出
stack
的最前节点,查询是否完成建树stack.top() == post[j]
,如果完成泽推出stack
。 - 把新建立的
node
设为stack
里面头节点的子数,要不然是左 要不然是右(就算只有一个节点,前序后序输出都是一样的) - 把新的
node
推入stack