二叉樹的遍歷:前序、中序、後序和層次遍歷
阿新 • • 發佈:2018-11-27
層次遍歷
/** * 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;
if(p==NULL) return res;
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;
}
};