Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
O(n)
,空间复杂度 O(h)
(h
为树高,平均为 log n
,最差为 n
)class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
dfs(root, res);
return res;
}
void dfs(TreeNode* root, vector<int>& res) {
if (!root) {
return;
}
dfs(root->left, res);
dfs(root->right, res);
res.emplace_back(root->val);
}
};
O(n)
,空间复杂度 O(n)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode* t = root;
TreeNode* last = root;
while (t || !empty(s)) {
while (t) {
s.emplace(t);
t = t->left;
}
t = s.top();
if (!t->right || t->right == last) {
s.pop();
res.emplace_back(t->val);
last = t;
t = nullptr;
} else {
t = t->right;
}
}
return res;
}
};