二叉树的三种遍历(非递归)
先定义二叉树:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
二叉树的先序遍历(以LeetCode 144.为例):
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>ans;
stack<TreeNode*>s;
s.push(root);
while(!s.empty()){
TreeNode *u=s.top();
s.pop();
if(u==NULL) continue;
ans.push_back(u->val);
if(u->right) s.push(u->right);
if(u->left) s.push(u->left);
}
return v;
}
};
二叉树的中序遍历(以LeetCode 94.为例):
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>ans;
stack<TreeNode*>s;
while(1){
while(root){
s.push(root);
root=root->left;
}
if(s.empty()) break;
root=s.top();
s.pop();
ans.push_back(root->val);
root=root->right;
}
return ans;
}
};
二叉树的后序遍历(以LeetCode 145.为例):
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>ans;
stack<TreeNode *>s;
s.push(root);
while(!s.empty()){
TreeNode *u=s.top();
s.pop();
if(u==NULL) continue;
ans.push_back(u->val);
s.push(u->left);
s.push(u->right);
}
reverse(ans.begin(),ans.end());
return ans;
}
};


浙公网安备 33010602011771号