二叉树的递归方式遍历
前序遍历
void preOrderRecur(Tree* tree)
{
if(tree==NULL) return ;
cout<<tree->data<<" ";
preOrderRecur(tree->lson);
preOrderRecur(tree->rson);
}
中序遍历
void inOrderRecur(Tree* tree)
{
if(tree==NULL) return ;
inOrderRecur(tree->lson);
cout<<tree->data<<" ";
inOrderRecur(tree->rson);
}
后序遍历
void posOrderRecur(Tree* tree)
{
if(tree==NULL) return ;
posOrderRecur(tree->lson);
posOrderRecur(tree->rson);
cout<<tree->data<<" ";
}
非递归形式的二叉树的三种遍历方式
前序遍历
void PreOrderRecur(Tree* tree)
{
stack<TreeNode*> sta;
while(!sta.empty()) sta.pop();
sta.push(tree);
while(!sta.empty()) {
Tree* cur = sta.top();
sta.pop();
cout<<cur->data<<" ";
if(cur->rson!=NULL) sta.push(cur->rson);
if(cur->lson!=NULL) sta.push(cur->lson);
}
}
中序遍历
void InOrderRecur(Tree* tree)
{
stack<TreeNode*> sta;
while(!sta.empty()) sta.pop();
while(!sta.empty() || tree!=NULL) {
if(tree==NULL) {
Tree* cur = sta.top();
sta.pop();
cout<<cur->data<<" ";
tree=cur->rson;
} else {
sta.push(tree);
tree=tree->lson;
}
}
}
后序遍历
一个栈的实现
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> order;
if(root == NULL)
return order;
stack<TreeNode*> s;
TreeNode *cur; //当前结点
TreeNode *pre=NULL; //前一次访问的结点
s.push(root);
while(!s.empty()) {
cur=s.top();
//如果当前结点没有孩子结点或者孩子节点都已被访问过
if((cur->left==NULL&&cur->right==NULL)|| (pre!=NULL&&(pre==cur->left||pre==cur->right))) {
order.push_back(cur->val);
s.pop();
pre=cur;
}
else {
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
}
return order;
}
两个栈的方法实现
void PosOrderRecur(Tree* tree)
{
stack<TreeNode*> sta;
stack<TreeNode*> Sta;
while(!sta.empty()) sta.pop();
while(!Sta.empty()) Sta.pop();
sta.push(tree);
while(!sta.empty()) {
Tree* cur = sta.top();
sta.pop();Sta.push(cur);
if(cur->lson!=NULL) sta.push(cur->lson);
if(cur->rson!=NULL) sta.push(cur->rson);
}
while(!Sta.empty()) {
cout<<Sta.top()->data<<" ";
Sta.pop();
}
}