leetcode上的第七题:
首先要知道后序遍历,是先遍历左子树、right tree、root这样;
边看代码边解释:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
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> res;
if (!root){
return res;
}
stack<TreeNode*> s;
int sign = 1;
TreeNode* p = NULL;
do{
while (root){
//printf("val :%d in stack\n", root->val);
s.push(root);
root = root->left;
}
p = NULL;
sign = 1;
while (!s.empty() && sign){
root = s.top();
if (root->right == p){
res.push_back(root->val);
p = root;
s.pop();
}
else{
sign = 0;
root = root->right;
}
}
} while (!s.empty());
return res;
}
};
int main(){
TreeNode* p1 = new TreeNode(3);
TreeNode* p2 = new TreeNode(1);
TreeNode* p3 = new TreeNode(2);
TreeNode* p4 = new TreeNode(-1);
p1->left = p2;
p1->right = p3;
p2->left = p4;
Solution s;
s.postorderTraversal(p1);
}
里面有个需要注意的地方,好吧,太晚了,赶紧洗洗睡了。
今天来公司暂时没什么事 就把之前写的中序、前序非递归遍历都写出来了:
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
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> res;
if (!root){
return res;
}
stack<TreeNode*> s;
int sign = 1;
TreeNode* p = NULL;
do{
while (root){
//printf("val :%d in stack\n", root->val);
s.push(root);
root = root->left;
}
p = NULL;
sign = 1;
while (!s.empty() && sign){
root = s.top();
if (root->right == p){
res.push_back(root->val);
p = root;
s.pop();
}
else{
sign = 0;
root = root->right;
}
}
} while (!s.empty());
return res;
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
if (!root){
return res;
}
stack<TreeNode*> s;
bool flag = false;
do{
while (root){
s.push(root);
root = root->left;
}
flag = false;
while (!s.empty()){
root = s.top();
s.pop();
printf("%d ", root->val);
if (root->right)
{
root = root->right;
flag = true;
break;
}
}
} while (!s.empty() || flag);
printf("\n");
return res;
}
vector<int> midorderTraversal(TreeNode *root) {
vector<int> res;
if (!root){
return res;
}
queue<TreeNode*> s;
do{
if (!s.empty())
{
root = s.front();
s.pop();
}
if(root){
printf("%d ", root->val);
if (root->left)
{
s.push(root->left);
}
if (root->right)
{
s.push(root->right);
}
}
} while (!s.empty());
printf("\n");
return res;
}
};
int main(){
TreeNode* p1 = new TreeNode(3);
TreeNode* p2 = new TreeNode(1);
TreeNode* p3 = new TreeNode(2);
TreeNode* p4 = new TreeNode(-1);
p1->left = p2;
p1->right = p3;
p2->left = p4;
Solution s;
s.midorderTraversal(p1);
}