#include <iostream> #include <cstdio> using namespace std; // 创建二叉树节点 typedef struct TreeNode{ char data; // 数据区 TreeNode* Lchild; // 左孩子 TreeNode* Rchild; // 右孩子 }*Tree; // Tree是我们通过typedef 创建的一种数据类型的别名 // 在当前的代码中 Tree, 是指向struct TreeNode结构体的别名 // 意味着Tree可以来声明和操作指向二叉树节点的指针, 并不用每次都完整的写出 struct TreeNode* t1; // 使用前序遍历创建二叉树 void CreateTree(Tree& T){ char x; cin >> x; if(x == '*'){ T = NULL; return; }else{ T = new TreeNode; T->data = x; CreateTree(T->Lchild); CreateTree(T->Rchild); } } // 前序遍历二叉树 void prev_order(const Tree& T){ if(T){ cout << T->data << " "; prev_order(T->Lchild); prev_order(T->Rchild); } } // 中序遍历二叉树 void midd_order(const Tree& T){ if(T){ midd_order(T->Lchild); cout << T->data << " "; midd_order(T->Rchild); } } // 后续遍历二叉树 void post_order(const Tree& T){ if(T){ post_order(T->Lchild); post_order(T->Rchild); cout << T->data << " "; } } // 判断二叉树是不是为空 bool TreeEmpty(const Tree& T){ if(T == NULL){ cout<< "二叉树为空" << endl; return true; }else{ cout<< "二叉树不为空" << endl; return false; } } // 求二叉树的节点数 int TreeNodeCount(const Tree& T){ if(T == NULL) return 0; else if(T->Lchild == NULL && T->Rchild == NULL) return 1; else return TreeNodeCount(T->Lchild) + TreeNodeCount(T->Rchild) + 1; } // 求二叉树的深度 int TreeDepth(const Tree& T){ if(T == NULL) return 0; else{ int i = TreeDepth(T->Lchild); int j = TreeDepth(T->Rchild); return max(i + 1, j + 1); } } int main(){ Tree T; cout << "请按照先序遍历输入, *表示没有左或者右节点:" << endl; CreateTree(T); // ABD**E**CF**G** cout << "先序遍历的结果为: "; prev_order(T); cout << endl; cout << "中序遍历的结果为: "; midd_order(T); cout << endl; cout << "后序遍历的结果为: "; post_order(T); cout << endl; cout << "树的节点数为: " << TreeNodeCount(T) << endl; cout << "树的深度为: " << TreeDepth(T) << endl; return 0; }
有话要说...