# Lintcode 66、67、68二叉树的前中后序遍历（递归、非递归实现）

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/

class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
//vector<int> res; //递归实现中初始化result，要放在函数体外
vector<int> preorderTraversal(TreeNode * root) {
//递归实现：
/* if(root != NULL){
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return res; */

//非递归实现：
TreeNode *x = root;
vector<int> result;
vector<TreeNode*> p;
while(x != NULL || p.size() != 0){
result.push_back(x->val);
if(x->right != NULL)
p.push_back(x->right);
x = x->left;
if(x == NULL && p.size() != 0){
x = p.back();
p.pop_back();
}
}
return result;
}
};

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/

class Solution {
public:
/**
* @param root: A Tree
* @return: Inorder in ArrayList which contains node values.
*/
//vector<int> result; //递归实现时初始化result要放在函数体外
vector<int> inorderTraversal(TreeNode * root) {
//非递归实现
/*vector<int> result;
vector<TreeNode*> p;
while(root != NULL || p.size() != 0){
while(root != NULL){
p.push_back(root);
root = root -> left;
}
root = p.back();
p.pop_back();
result.push_back(root -> val);
root = root -> right;
}
return result; */

//递归实现
if(root != NULL){
inorderTraversal(root -> left);
result.push_back(root -> val);
inorderTraversal(root -> right);
}
return result;
}
};

1.申请一个栈，记为s1，然后将头节点压入s1中。
2.从s1中弹出的节点，然后依次将节点的左孩子和右孩子压入s1中。
3.在整个过程中，每一个从s1中弹出的节点都放进s2中。
4.不断重复步骤2和步骤3，直到s1为空，过程停止。
5.从s2中依次弹出节点并打印，打印的顺序就是后序遍历的顺序。

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/

class Solution {
public:
/**
* @param root: A Tree
* @return: Postorder in ArrayList which contains node values.
*/
vector<int> result; //递归遍历初始化result
vector<int> postorderTraversal(TreeNode * root) {
//非递归遍历
/* vector<int> result;
if(root == NULL)
return result;
vector<TreeNode*> s1;
vector<TreeNode*> s2;
s1.push_back(root);
while(s1.size() != 0){
TreeNode* temp1 = s1.back();
s2.push_back(temp1);
s1.pop_back();
if(temp1 -> left != NULL)
s1.push_back(temp1 -> left);
if(temp1 -> right != NULL)
s1.push_back(temp1 -> right);
}
while(s2.size() != 0){
TreeNode* temp2 = s2.back();
result.push_back(temp2 -> val);
s2.pop_back();
}
return result; */

//递归遍历
if(root != NULL){
postorderTraversal(root -> left);
postorderTraversal(root-> right);
result.push_back(root -> val);
}
return result;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120