#include <iostream>
#include <stack>
using namespace std;
class BinNode{
public:
char data;
BinNode* lChild;
BinNode* rChild;
public:
BinNode(char data, BinNode* lChild=nullptr, BinNode* rChild=nullptr){
this->data = data;
this->lChild = lChild;
this->rChild = rChild;
}
};
class BinTree{
public:
BinNode* root;
public:
//构造空树
BinTree(){
root = nullptr;
}
//构造只有根结点的树
BinTree(char data){
root = new BinNode(data);
}
//析构函数
~BinTree(){
delete root;
}
//以扩展二叉树前序遍历序列创建二叉树,空树时输入为#
void createTree(BinNode*& root){
char data;
cin >> data;
if(data != '#'){
root = new BinNode(data);
createTree(root->lChild);
createTree(root->rChild);
}
else{
root = nullptr;
}
}
//递归前序遍历
void preOrder(BinNode*& root){
BinNode* cur = root;
if(cur){
cout << cur->data << endl;
preOrder(cur->lChild);
preOrder(cur->rChild);
}
}
//非递归前序遍历
void preOrder_2(BinNode*& root){
BinNode* cur = root;
stack<BinNode*> stack;
while(cur || !stack.empty()){
while(cur){
cout << cur->data << endl;
cur = cur->lChild;
stack.push(cur->rChild);//沿路将右子树记录下来表示未曾访问
}
//遇到空树则回溯处理右子树
cur = stack.top();
stack.pop();
}
}
//递归中序遍历
void inOrder(BinNode*& root){
BinNode* cur = root;
if(cur){
inOrder(cur->lChild);
cout << cur->data << endl;
inOrder(cur->rChild);
}
}
//非递归中序遍历
void inOrder_2(BinNode*& root){
BinNode* cur = root;
stack<BinNode*> stack;
while(cur || !stack.empty()){
while(cur){
stack.push(cur);
cur = cur->lChild;
}
cur = stack.top();
stack.pop();
cout << cur->data << endl;
cur = cur->rChild;
}
}
//递归后序遍历
void postOrder(BinNode*& root){
BinNode* cur = root;
if(cur){
postOrder(cur->lChild);
postOrder(cur->rChild);
cout << cur->data << endl;
}
}
//非递归后序遍历
void postOrder_2(BinNode*& root){
BinNode* cur = root;
stack<BinNode*> stack;
while(cur || !stack.empty()){
while(cur){
stack.push(cur);
//能左就左,否则向右
if(cur->lChild)
cur = cur->lChild;
else
cur = cur->rChild;
}
cur = stack.top();
stack.pop();
cout << cur->data << endl;
if(!stack.empty() && cur==stack.top()->lChild)
//stack非空,因为stack.top()用到了stack,如果是空的,则引发错误
//如果被访问的结点是其父的左结点,直接转到其右兄弟结点继续
cur = stack.top()->rChild;
else
//如果被访问的结点是其父的右结点,设cur为空,强制访问更上一层结点
cur = nullptr;
}
}
int size(BinNode*& root){
if(root){
int sl = size(root->lChild);
int sr = size(root->rChild);
return sl+sr+1;
}
else{
return 0;
}
}
int height(BinNode*& root){
if(root){
int hl = height(root->lChild);
int hr = height(root->rChild);
return hl>hr?hl+1:hr+1;
}
else{
return 0;
}
}
};
int main(){
BinTree tree;
tree.createTree(tree.root);
tree.postOrder(tree.root);
tree.postOrder_2(tree.root);
return 0;
}
二叉树C++版
最新推荐文章于 2023-04-13 11:31:14 发布