建立一颗二叉树:
#include "handsomecui.h" typedef struct Node{ char data; Node *left, *right; }Node, *Tree; Tree build(){ char c; SI(c); if(c == ‘#‘){ return NULL; } else{ Node *root = new Node; root->data = c; root->left = build(); root->right = build(); return root; } } void VisitTree(Node *root){ if(root == NULL){ return; } VisitTree(root->left); VisitTree(root->right); PI(root->data); } int main(){ Tree tree = build(); VisitTree(tree); return 0; }
按层遍历:
#include "handsomecui.h" #include<queue> typedef struct Node{ char data; Node *left, *right; }Node, *Tree; Tree build(){ char c; SI(c); if(c == ‘#‘){ return NULL; } else{ Node *root = new Node; root->data = c; root->left = build(); root->right = build(); return root; } } void Floor_Visit(Node *root){ queue<Tree>Q; Q.push(root); while(!Q.empty()){ root = Q.front(); Q.pop(); PI(root->data); if(root->left != NULL) Q.push(root->left); if(root->right != NULL) Q.push(root->right); } } int main(){ Tree tree = build(); PI("按层访问的结果为:\n"); Floor_Visit(tree); return 0; }
结点总数,页结点以及深度:
#include "handsomecui.h" typedef struct Node{ char data; Node *left, *right; }Node, *Tree; Tree build(){ char c; SI(c); if(c == ‘#‘){ return NULL; } else{ Node *root = new Node; root->data = c; root->left = build(); root->right = build(); return root; } } int Total_Node(Node *root){ if(root == NULL) return 0; else return Total_Node(root->left) + Total_Node(root->right) + 1; } int Child_Node(Node *root){ if(root->left == NULL && root->right == NULL){ return 1; } else{ int temp = 0; if(root->left != NULL) temp += Child_Node(root->left); if(root->right != NULL) temp += Child_Node(root->right); return temp; } } int Tree_Depth(Node *root){ if(root == NULL) return 0; else return max(Tree_Depth(root->left), Tree_Depth(root->right)) + 1; } int main(){ Tree tree = build(); PI("这棵二叉树的总结点为"); PI(Total_Node(tree)); PI("\n这棵二叉树的页结点为"); PI(Child_Node(tree)); PI("\n这棵二叉树的深度为"); PI(Tree_Depth(tree)); return 0; }
时间: 2024-10-12 03:23:07