树的先序、中序、后序(非递归)
先序
class Solution {
public:
void dfs(TreeNode* root,vector<int>& v)
{
stack<TreeNode*>s;
while(root||!s.empty())
{
while(root!=NULL)
{
s.push(root);
v.push_back(root->val);
root = root->left;
}
root = s.top();
s.pop();
root = root->right;
}
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int>v;
if(root)
dfs(root,v);
return v;
}
};
中序
class Solution {
public:
void dfs(TreeNode* root,vector<int>& v)
{
stack<TreeNode*>s;
while(root||!s.empty())
{
while(root!=NULL)
{
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
v.push_back(root->val);
root = root->right;
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int>v;
if(root)
dfs(root,v);
return v;
}
};
后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>v;
if(root==NULL)
return v;
stack<TreeNode*>s;
s.push(root);
while(!s.empty())
{
TreeNode* node=s.top();
s.pop();
v.push_back(node->val);
if(node->left!=NULL)
s.push(node->left);
if(node->right!=NULL)
s.push(node->right);
}
for(int i=0,j=v.size()-1;i<j;i++,j--)
swap(v[i],v[j]);
return v;
}
};