前序
非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stack>
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> mystack;
vector<int> ans;
if (!root) {
return ans;
}
TreeNode* current = root;
while (current || !mystack.empty()) {
if (!current) {
current = mystack.top();
mystack.pop();
}
ans.push_back(current->val);
if (current->right) {
mystack.push(current->right);
}
current = current->left;
}
return ans;
}
};
// 更好的写法
#include <stack>
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> mystack;
vector<int> ans;
if (!root) {
return ans;
}
mystack.push(root);
while (!mystack.empty()) {
TreeNode* current = mystack.top();
mystack.pop();
ans.push_back(current->val);
// 先右后左
if (current->right) mystack.push(current->right);
if (current->left) mystack.push(current->left);
}
return ans;
}
};
递归
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
preorder(root);
return ans;
}
void preorder(TreeNode* root) {
if (root) {
ans.push_back(root->val);
preorder(root->left);
preorder(root->right);
}
}
};
后序
非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stack>
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> mystack;
if (!root) {
return ans;
}
TreeNode* pre = nullptr;
mystack.push(root);
while (!mystack.empty()) {
TreeNode* current = mystack.top();
// 当前节点是叶子结点或者子节点都已被访问过
if ((!current->left && !current->right) || (pre && (pre == current->left || pre == current->right)) ) {
ans.push_back(current->val);
pre = current;
mystack.pop();
} else {
// 先右后左
if (current->right) mystack.push(current->right);
if (current->left) mystack.push(current->left);
}
}
return ans;
}
};
// 由前序变换得来
#include <stack>
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> mystack;
vector<int> ans;
if (!root) {
return ans;
}
mystack.push(root);
while (!mystack.empty()) {
TreeNode* current = mystack.top();
mystack.pop();
// 插在最前面
ans.insert(ans.begin(), current->val);
// 先左后右
if (current->left) mystack.push(current->left);
if (current->right) mystack.push(current->right);
}
return ans;
}
};
递归
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode* root) {
postorder(root);
return ans;
}
void postorder(TreeNode* root) {
if (root) {
postorder(root->left);
postorder(root->right);
ans.push_back(root->val);
}
}
};
总结
- 非递归 前序的每次都循环都有出栈 有出栈即有访问;后序的要满足要求才出栈,即满足要求才访问。
- 前序 根 左 右 后序 左 右 根 。可以取巧用前序变形来替换后序。