1、二叉树的遍历
(1)前序遍历
1)递归方法
void pre(BinTree* root){
if(root == nullptr) return;
cout << root->val << ',';
pre(root->left);
pre(root->right);
}
2)非递归方法:先将右孩子压栈,再将左孩子压栈
void pre_nore(BinTree* root){
if(root){
stack<BinTree*> s;
s.push(root);
while(!s.empty()){
cout << s.top()->val << ',';
root = s.top();
s.pop();
if(root->right != nullptr){
s.push(root->right);
}
if(root->left != nullptr){
s.push(root->left);
}
}
}
}
(2)中序遍历
1)递归方法
void middle(BinTree* root){
if(root == nullptr) return;
middle(root->left);
cout << root->val << ',';
middle(root->right);
}
2)非递归的方法
void middle_nore(BinTree* root){
if(root){
stack<BinTree*> s;
while(!s.empty() || root != nullptr){
if(root != nullptr){
s.push(root);
root = root->left;
}
else{
cout << s.top()->val << ',';
root = s.top()->right;
s.pop();
}
}
}
}
(3)后序遍历
1)递归方法
void back(BinTree* root){
if(root == nullptr) return;
back(root->left);
back(root->right);
cout << root->val << ',';
}
2)非递归方法1:两个栈
void back_nore1(BinTree* root){
if(root){
stack<BinTree*> s1;
stack<int> s2;
s1.push(root);
while (!s1.empty())
{
root = s1.top();
s2.push(root->val);
s1.pop();
if(root->left != nullptr){
s1.push(root->left);
}
if(root->right != nullptr){
s1.push(root->right);
}
}
while(!s2.empty()){
cout<< s2.top()<<',';
s2.pop();
}
}
}
3)非递归的方法2
void back_nore2(BinTree* root){
if(root){
stack<BinTree*> s;
BinTree* c; //指向栈顶元素
BinTree* h = root; //指向刚被弹出的位置
s.push(root);
while (!s.empty())
{
c = s.top();
if(c->left != nullptr && h != c->left && h != c->right){
s.push(c->left);
}
else if(c->right != nullptr && h != c->right){
s.push(c->right);
}
else{
cout << c->val << ',';
h = c;
s.pop();
}
}
}
}
2、二叉树的层序遍历
void level_traverse(BinTree* root){
if(root){
queue<BinTree*> Q;
BinTree* CurEnd = root;
BinTree* nextEnd = nullptr;
Q.push(root);
while(!Q.empty()){
BinTree* curNode = Q.front();
cout << curNode->val << ',';
Q.pop();
if(curNode->left != nullptr){
Q.push(curNode->left);
nextEnd = curNode->left;
}
if(curNode->right != nullptr){
Q.push(curNode->right);
nextEnd = curNode->right;
}
if(curNode == CurEnd){
CurEnd = nextEnd;
cout << endl;
}
}
}
}