二叉树遍历
Contents
前序遍历
void preorder(Node * head){
if(head!=null)
{
cout << head -> val;
preorder(head->left);
preorder(head->right);
}
}
void preorder(Node * head){
if(!head)
return ;
stack<Node *> s;
s.push(head);
while(!s.empty()){
Node * tmp = s.top();
s.pop();
cout << tmp.val;
if(tmp->left)
s.push(tmp->left);
if(tmp->right)
s.push(tmp->right);
}
}
中序遍历
void inorder(Node * head){
if(head!=null)
{
inorder(head->left);
cout << head -> val;
inorder(head->right);
}
}
void inorder(Node * head){//一直将他的左子树压栈。 一直到左子树最左的节点
if(!head)
return ;
stack<Node*> s;
s.push(head);
while(!s.empty() || head!=nullptr){
if(head->left!=nullptr)
s.push(head->left);
else{
head = s.top();
s.pop();
cout << head->val;
if(head->right!=nullptr)
s.push(head.right);
}
}
}
后序遍历
void laterorder(Node * head){
if(head!=null)
{
laterorder(head->left);
laterorder(head->right);
cout << head -> val;
}
}
void laterorder(Node * head){//维护两个栈,第一个栈遍历顺序 中右左; 第二个 左右中。
if(!head)
return ;
stack<Node * > s1,s2;
s1.push(head);
while(!s1.empty()){
head = s1.top();
s1.pop();
s2.push(head);
if(head->left)
s1.push(head->left);
if(head->right)
s1.push(head->right);
}
while(!s2.empty()){
head = s2.top();
s2.pop();
cout << head->val;
}
}