二叉树的深度
二叉树的递归简历
二叉树的递归前序遍历
二叉树的递归深度求解
示例:
10
6
4
0
0
0
14
12
0
0
16
0
0
10 6 4 14 12 16
3
1 #include <iostream>
2 using namespace std;
3
4 struct node
5 {
6 int value;
7 node* left;
8 node* right;
9 };
10
11 void create(node*& btree)
12 {
13 int n;
14 cin >> n;
15 if (n == 0)
16 {
17 btree = 0;
18 }
19 else
20 {
21 btree = new node;
22 btree->value = n;
23 create(btree->left);
24 create(btree->right);
25 }
26 }
27
28 void preOrder(node* btree)
29 {
30 if (btree != 0)
31 {
32 cout << btree->value << ' ';
33 preOrder(btree->left);
34 preOrder(btree->right);
35 }
36 }
37
38 int depth(node* btree)
39 {
40 if (btree == 0)
41 {
42 return 0;
43 }
44 else
45 {
46 int left = depth(btree->left);
47 int right = depth(btree->right);
48 return left > right ? left + 1 : right + 1;
49 }
50 }
51
52 int main()
53 {
54 node* btree;
55 create(btree);
56 preOrder(btree);
57 cout << endl;
58 cout << depth(btree) << endl;
59 }
posted on 2011-09-13 12:41
unixfy 阅读(160)
评论(0) 编辑 收藏 引用