二叉树的插入,递归遍历和深度节点数
二叉树的插入,前序,中序,后序遍历,递归求深度和节点数
View Code
#include<stdlib.h> #include<stdio.h> struct tree_el { int val; struct tree_el * right, * left; }; typedef struct tree_el node; void insert(node ** tree, node * item) { if(!(*tree)) { *tree = item; return; } if(item->val<=(*tree)->val) insert(&(*tree)->left, item); else if(item->val>(*tree)->val) insert(&(*tree)->right, item); } void InOrd(node * tree) { if(tree->left) InOrd(tree->left); printf("%d ",tree->val); if(tree->right) InOrd(tree->right); } void PreOrd(node *tree) { printf("%d ",tree->val); if(tree->left) PreOrd(tree->left); if(tree->right) PreOrd(tree->right); } void PostOrd(node *tree) { if(tree->left) PostOrd(tree->left); if(tree->right) PostOrd(tree->right); printf("%d ",tree->val); } int TreeDepth(node* tree) { // the depth of a empty tree is 0 if(!tree) return 0; // the depth of left sub-tree int nLeft = TreeDepth(tree->left); // the depth of right sub-tree int nRight = TreeDepth(tree->right); // depth is the binary tree return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1); } int BTreeNodeCount(node *tree) { if(tree == 0) return 0; else { int l = BTreeNodeCount(tree->left); int r = BTreeNodeCount(tree->right); return l + r + 1; } } int main() { node * curr, * root; int i; int data; int lenth; root = NULL; printf("请输入要插入的元素,按Ctrl + Z结束输入\n"); while(scanf("%d",&data)!= EOF) { curr = (node *)malloc(sizeof(node)); curr->left = curr->right = NULL; curr->val = data; insert(&root, curr); } printf("先序遍历 : "); PreOrd(root); printf("\n中序遍历 : "); InOrd(root); printf("\n后序遍历 : "); PostOrd(root); printf("\n树的深度为 : %d\n", TreeDepth(root)); printf("树的节点数为:%d\n", BTreeNodeCount(root)); return 0; }