1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <iostream> #include <queue>
using namespace std;
typedef struct node{ char data; node *parent,*left,*right; }Treenode,*BiTree;
typedef struct BinaryTree{ Treenode *root; int deepth; int num; };
void CreatTree(BiTree &t){ char c; cin>>c; if (c == '*'){ t = NULL; } else{ t = new (node); t->data = c; CreatTree(t->left); CreatTree(t->right); } return; }
void DFS(node* node) { if (node==NULL){ return;; } cout<<node->data<<"->"; if (node->left!=NULL) DFS(node->left); if (node->right!=NULL) DFS(node->right); }
void prettyPrintTree(node* node, string prefix = "", bool isLeft = true) { if (node == NULL) { cout << "Empty tree"; return; } if(node->right) { prettyPrintTree(node->right, prefix + (isLeft ? "│ " : " "), false); } cout << prefix + (isLeft ? "└── " : "┌── ") + node->data + "\n"; if (node->left) { prettyPrintTree(node->left, prefix + (isLeft ? " " : "│ "), true); } }
void Mirror(Treenode *node){ if (node == NULL){ return; } swap(node->left,node->right); Mirror(node->left); Mirror(node->right); }
int TreeDepth(Treenode *node){ if(node==NULL) return 0; int left=TreeDepth(node->left)+1; int right=TreeDepth(node->right)+1; return left>right?left:right; }
int leaf(Treenode *node,int &sum){ if (node==NULL){ return 0; } if (node->left == NULL&&node->right == NULL){ sum++; } if (node->left!=NULL) leaf(node->left,sum); if (node->right!=NULL) leaf(node->right,sum); return sum; }
int main() { int sum=0; BinaryTree t; CreatTree(t.root); DFS(t.root); cout<<endl; prettyPrintTree(t.root); leaf(t.root,sum); cout<<"叶子个数为:"<<sum<<endl; cout<<"深度为:"<<TreeDepth(t.root)<<endl; Mirror(t.root); DFS(t.root); cout<<endl; prettyPrintTree(t.root); return 0; }
|