树结构
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
中序遍历
vector<int> midorderTraversal(TreeNode *root)
{
vector<int> temp;
stack<TreeNode *> s;
bool left = false;
bool right = false;
if(root == NULL)
return temp;
TreeNode* p = root;
while(p ||!s.empty()){
if(p != NULL){
s.push(p);
p = p->left;
}else{
p = s.top();
temp.push_back(p->val);
s.pop();
p = p->right;
}
}
vector<int>::const_iterator iter = temp.begin();
while(iter != temp.end()){
cout<<*iter<<"\t";
iter++;
}
cout<<endl;
}
前序遍历
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> temp;
stack<TreeNode *> s;
s.push(root);
if (!root) return temp;
while (!s.empty())
{
TreeNode *p = s.top();
s.pop();
temp.push_back(p->val);
if (p->right) s.push(p->right);
if (p->left) s.push(p->left);
}
vector<int>::const_iterator iter = temp.begin();
while(iter != temp.end()){
cout<<*iter<<"\t";
iter++;
}
cout<<endl;
return temp;
}
后序遍历
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> temp;
stack<TreeNode *> s;
if(root == NULL)
return temp;
TreeNode *p = root;
s.push(p);
while(!s.empty()){
p = s.top();
s.pop();
temp.insert(temp.begin(),p->val);
if(p->left != NULL) s.push(p->left);
if(p->right != NULL) s.push(p->right);
}
vector<int>::const_iterator iter = temp.begin();
while(iter != temp.end()){
cout<<*iter<<"\t";
iter++;
}
cout<<endl;
}