层次遍历
/**
* 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<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode *> q;
if(root==NULL) return res ;
q.push(root);
vector<int> tmp;
TreeNode * p = NULL;
while(!q.empty()){
int n = q.size();
tmp.clear();
for(int i=0;i<n;i++){
p = q.front();
q.pop();
tmp.push_back(p->val);
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
res.push_back(tmp);
}
return res;
}
};
参考资料:https://blog.csdn.net/zgaoq/article/details/79089819
前序
非递归实现
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode *> s;
TreeNode * p = root;
while(!s.empty() || p){
while(p){
res.push_back(p->val);
s.push(p);
p=p->left;
}
p = s.top();
s.pop();
p=p->right;
}
return res;
}
};
中序
非递归实现
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> res;
TreeNode * p = root;
stack<TreeNode *> s;
while(!s.empty() || p){
while(p){
s.push(p);
p = p->left;
}
p = s.top();
s.pop();
res.push_back(p->val);
p = p->right;
}
return res;
}
};
后序
非递归实现
/**
* 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> res;
stack<TreeNode *> s;
TreeNode * p = root, * preVisit = NULL;
while(p){
s.push(p);
p = p->left;
}
while(!s.empty()){
p = s.top();
if(p->right==NULL || p->right==preVisit){
s.pop();
res.push_back(p->val);
preVisit = p;
}else{
p = p->right;
while(p){
s.push(p);
p=p->left;
}
}
}
return res;
}
};