Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
后序遍历就是:左->右->root的遍历方式(因为root在后面),同样有两种解决方案,但是请注意,后序遍历的难度是hard,所以在用非递归的方式实现的过程也更复杂一些。
1 递归的实现方案
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
vector<int> left;
vector<int> right;
if (root->left) left = postorderTraversal(root->left);
if (root->right) right = postorderTraversal(root->right);
if (!left.empty()) {
res = left;
}
if (!right.empty()) {
res.insert(res.end(), right.begin(), right.end());
}
res.push_back(root->val);
return res;
}
2 利用栈完成遍历
vector<int> postorderTraversal2(TreeNode* root) {
vector<int> res;
if (!root) return res;
stack<TreeNode*> s;
TreeNode* lastV = NULL;
TreeNode* tmp = root;
while (!s.empty() || tmp) {
if (tmp) {
s.push(tmp);
tmp = tmp->left;
}
else {
TreeNode* n = s.top();
if (n->right && lastV != n->right) {
tmp = n->right;
}
else {
res.push_back(n->val);
s.pop();
lastV = n;
}
}
}
return res;
}