题目描述:
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1]
AC C++ Solution:
堆栈迭代解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> nodes;
stack<TreeNode*> todo;
TreeNode* cur = root;
TreeNode* last = NULL;
while (cur || !todo.empty()) {
if (cur) {
todo.push(cur);
cur = cur -> left;
} else {
TreeNode* top = todo.top();
if (top -> right && (last != top -> right)) {
cur = top -> right;
} else {
nodes.push_back(top -> val);
last = top;
todo.pop();
}
}
}
return nodes;
}
};
递归解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//递归
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> nodes;
postorder(root, nodes);
return nodes;
}
private:
void postorder(TreeNode* root, vector<int>& nodes) {
if (!root) {
return;
}
postorder(root -> left, nodes);
postorder(root -> right, nodes);
nodes.push_back(root -> val);
}
};
同样,递归解法一目了然,推广到其它两种遍历也很简单。