数据结构二叉树有遍历的想法

it2026-08-05  8

#include<iostream> #include<stdlib.h> using namespace std; #define LEN 30 typedef struct TreeNode{ int data; TreeNode *LChild;//左节点 TreeNode *RChild;//右节点 }TreeNode; //按照从左到右,从上到下给二叉树赋值 TreeNode *init(int *init_arr,int lens){ TreeNode *TreeArr[LEN]; //先形成一个数组 int i; for(i=0;i<lens;i++){ if(init_arr[i]!=0){ TreeArr[i]=(TreeNode *)malloc(sizeof(TreeNode)); TreeArr[i]->data=init_arr[i]; TreeArr[i]->LChild=NULL; TreeArr[i]->RChild=NULL; }else TreeArr[i]=NULL; } //再把他们串成链表 int len=lens/2; for(i=0;i<len;i++){ if(TreeArr[i]!=NULL){ TreeArr[i]->LChild=TreeArr[2*i+1]; TreeArr[i]->RChild=TreeArr[2*i+2]; } } return TreeArr[0]; } //先序遍历 void PreOrder(TreeNode *head){ if(head!=NULL){ cout<<head->data<<" "; PreOrder(head->LChild); PreOrder(head->RChild); } } //中序遍历 void InOrder(TreeNode *head){ if(head!=NULL){ InOrder(head->LChild); cout<<head->data<<" "; InOrder(head->RChild); } } //后续遍历 void PostOrder(TreeNode *head){ if(head!=NULL){ PostOrder(head->LChild); PostOrder(head->RChild); cout<<head->data<<" "; } } //输出二叉树叶子节点 void print_leaf_node(TreeNode *root){ if(root!=NULL){ if(root->LChild==NULL&&root->RChild==NULL)cout<<root->data<<" "; print_leaf_node(root->LChild); print_leaf_node(root->RChild); } } //统计叶子节点个数:方法一 int Leaf_count=0; void leaf_num1(TreeNode *root){ if(root!=NULL){ leaf_num1(root->LChild); leaf_num1(root->RChild); if(root->LChild==NULL&&root->RChild==NULL)Leaf_count++; } } //统计叶子节点个数:方法二 int leaf_num2(TreeNode *root){ if(root==NULL){ return 0; }else if(root->LChild==NULL&&root->RChild==NULL){ return 1; }else{ return (leaf_num2(root->LChild)+leaf_num2(root->RChild)); } } //求二叉树高度:先序遍历 int depth=0; void Pre_tree_depth(TreeNode * head, int h){ if(head!=NULL){ if(h>depth)depth=h; Pre_tree_depth(head->LChild,h+1); Pre_tree_depth(head->RChild,h+1); } } int main(int argc, char const *argv[]) { TreeNode *head=(TreeNode *)malloc(sizeof(TreeNode)); int init_arr[]={1,2,3,0,4,0,5};//0表示 head=init(init_arr,7);//传数组跟数组的长度 PreOrder(head);//先序遍历输出 cout<<endl; // InOrder(head);//中序遍历 // cout<<endl; // PostOrder(head);//后续遍历 // cout<<endl; // print_leaf_node(head);//输出叶子节点 // cout<<endl; // leaf_num1(head);//输出叶子节点:方法一 // cout<<"叶子节点个数:"<<Leaf_count<<endl; // int num=leaf_num2(head);//输出叶子节点:方法二 // cout<<"叶子节点个数:"<<num<<endl; // Pre_tree_depth(head,0); // cout<<"二叉树深度:"<<depth<<endl; return 0; }
最新回复(0)