二叉树中序遍历递归算法,求树的高度,以及拷贝树

来源:互联网 发布:java 判断true false 编辑:程序博客网 时间:2024/05/03 20:00
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct BiTNode{int date;struct BiTNode *lchild, *rchild;//二叉树左枝,右枝}BiTNode;void inOrder(BiTNode *root)//中序遍历递归算法{if (root == NULL){return;}inOrder(root->lchild);//遍历左枝printf("%d  ", root->date);//打印节点inOrder(root->rchild);//遍历右枝}int Depth(BiTNode * root)//递归求树的高度{int DepthLeft = 0;//左树高度int DephRight = 0;//右树高度int DepthLast = 0;//最后树的高度if (root == NULL){return 0;}DepthLeft = Depth(root->lchild);DephRight = Depth(root->rchild);DepthLast = 1 + (DepthLeft > DephRight ? DepthLeft : DephRight);return DepthLast;}BiTNode * CopyTree(BiTNode * root){if (root == NULL){return NULL;}BiTNode * NewNode = NULL;BiTNode * NewLef = NULL;BiTNode * NewRig = NULL;if (root->lchild != NULL){NewLef = CopyTree(root->lchild);}else{NewLef = NULL;}if (root->rchild != NULL){NewRig = CopyTree(root->rchild);}else{NewRig = NULL;}NewNode = (BiTNode *)malloc(sizeof(BiTNode));if (NewNode == NULL){return NULL;}NewNode->lchild = NewLef;NewNode->rchild = NewRig;NewNode->date = root->date;return NewNode;}void main(){BiTNode t1, t2, t3, t4, t5;memset(&t1, 0, sizeof(BiTNode));//初始化内存的数据memset(&t2, 0, sizeof(BiTNode));memset(&t3, 0, sizeof(BiTNode));memset(&t4, 0, sizeof(BiTNode));memset(&t5, 0, sizeof(BiTNode));t1.date = 1;t2.date = 2;t3.date = 3;t4.date = 4;t5.date = 5;t1.lchild = &t2;t1.rchild = &t3;t2.rchild = &t4;t3.lchild = &t5;int height = Depth(&t1);printf("树的高度:%d\n",height);printf("*********************\n递归算法中序遍历:\n");inOrder(&t1);printf("\n*********************\n");BiTNode *tmp = NULL;tmp = CopyTree(&t1);printf("*********************\n递归算法中序遍历:\n");inOrder(tmp);printf("\n*********************\n");system("pause");}

0 0
原创粉丝点击