转载 二叉树的创建、遍历、深度、叶子节点数

  1 # include <stdio.h>
2 # include <malloc.h>
3 typedef struct BiTNode{
4 struct BiTNode *lchild;
5 struct BiTNode *rchild;
6 }treeNode, *tNode;
7 void createTree(int a[])
8 {
9 }
10 /**
11 * 插入节点到二叉树中
12 */
13 void insert(tNode root,int data)
14 {
15 tNode newNode = (tNode)malloc(sizeof(treeNode));
16 newNode->data = data;
17 newNode->lchild = NULL;
18 newNode->rchild = NULL;
19 tNode current = root;
20 tNode parent;
21 while (1)
22 {
23 parent = current;
24 if (current->data > newNode->data)
25 {
26 current = current->lchild;
27 if (current == NULL)
28 {
29 parent->lchild = newNode;
30 return;
31 }
32 }
33 else
34 {
35 current = current->rchild;
36 if (current == NULL)
37 {
38 parent->rchild = newNode;
39 return;
40 }
41 }
42 }
43 }
44 /**
45 * 递归中序遍历二叉树
46 */
47 void preOrder(tNode root)
48 {
49 if (root != NULL)
50 {
51 preOrder(root->lchild);
52 printf("%d ",root->data);
53 preOrder(root->rchild);
54 }
55 }
56 /**
57 * 求二叉树叶子节点数目
58 */
59 int getLeaf(tNode root)
60 {
61 if (root == NULL)
62 return 0;
63 else
64 if (root->lchild == NULL && root->rchild == NULL)
65 return 1;
66 else
67 return getLeaf(root->lchild) + getLeaf(root->rchild);
68 }
69 /**
70 * 求二叉树的深度
71 */
72 int getDepth(tNode root)
73 {
74 if (root == NULL)
75 return 0;
76 else
77 return getDepth(root->lchild) > getLeaf(root->rchild)? 1 + getDepth(root->lchild): 1 + getDepth(root->rchild);
78 // {
79 // int depthLchild = 1 + getDepth(root->lchild);
80 // int depthRchild = 1 + getDepth(root->rchild);
81 // return depthLchild > depthRchild ? depthLchild: depthRchild;
82 // }
83 }
84 int main()
85 {
86 tNode root = (tNode)malloc(sizeof(treeNode));
87 root->data = 10;
88 root->lchild = NULL;
89 root->rchild = NULL;
90 // insert(root,10);
91 insert(root,5);
92 insert(root,15);
93 insert(root,1);
94 insert(root,8);
95 insert(root,20);
96 insert(root,12);
97 preOrder(root);
98 printf("/n");
99 int numleaf = getLeaf(root);
100 printf("%d/n", numleaf);
101 int depth = getDepth(root);
102 printf("%d/n",depth);
103 return 0;
104 }

编辑器加载中...

posted on 2011-08-11 20:36  kyleada  阅读(537)  评论(0编辑  收藏  举报

导航