LoveFM

导航

LevelOrderBTree

  1 #include<iostream>
2 #include<deque>
3 #include<stdlib.h>
4 using namespace std;
5
6 static int k=1;
7
8 struct BinaryTreeNode{
9 BinaryTreeNode* m_pLeft;
10 BinaryTreeNode* m_pRight;
11 int m_nValue;
12 };
13
14
15 //从上到下的层次访问该二叉树(每一层将单独输出一行),每一层要求访问的顺序为从左到右
16 void LevelOrderBTree(const BinaryTreeNode* root)
17 {
18 deque<const BinaryTreeNode*> store;
19 int left_num;
20 if(!root)
21 return;
22
23 store.push_back(root);
24
25 while(!store.empty()){
26 left_num = store.size(); // 当前层的节点数
27
28 while(left_num-- > 0) {
29 const BinaryTreeNode* tmp = store.front();
30 store.pop_front();
31
32 cout << tmp->m_nValue << "";
33
34 if(tmp->m_pLeft)
35 store.push_back(tmp->m_pLeft);
36 if(tmp->m_pRight)
37 store.push_back(tmp->m_pRight);
38 }
39 cout << endl;
40 }
41 }
42
43
44 //输出二叉树某一层结点(从左到右)
45 void PrintNodeAtLevel(BinaryTreeNode *root,int level)
46 {
47 if(!root || level < 0)
48 return ;
49 if(level == 0 ){
50 cout << root->m_nValue << "";
51 }
52 PrintNodeAtLevel(root->m_pLeft,level-1);
53 PrintNodeAtLevel(root->m_pRight,level-1);
54 }
55
56 //输出二叉树第 m 层的第 k 个节点值(m, k 均从 0 开始计数)
57 int mLevelKnode(BinaryTreeNode *root , int m , int *cnt)
58 {
59 if(!root || m < 0)
60 return 0;
61 if(m == 0)
62 {
63 if(*cnt == k)
64 {
65 cout << root->m_nValue << "";
66 return 1;
67 }
68 *cnt += 1;
69 return 0;
70 }
71 return mLevelKnode(root->m_pLeft, m - 1 , cnt) || mLevelKnode(root->m_pRight , m - 1 , cnt);
72 }
73
74
75 void addTree(BinaryTreeNode **T, int num)
76 {
77 if(*T == NULL)
78 {
79 *T = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
80 (*T)->m_nValue = num;
81 (*T)->m_pLeft = NULL;
82 (*T)->m_pRight = NULL;
83 }
84 else if((*T)->m_nValue > num)
85 addTree(&((*T)->m_pLeft), num);
86 else if((*T)->m_nValue < num)
87 addTree(&((*T)->m_pRight), num);
88 else
89 cout << "重复加入同一结点" << endl;
90 }
91
92 int main()
93 {
94 int cnt=0;
95
96 BinaryTreeNode * T = NULL;
97 addTree(&T, 10);
98 addTree(&T, 12);
99 addTree(&T, 5);
100 addTree(&T, 7);
101 addTree(&T, 4);
102
103 LevelOrderBTree(T);//从上到下的层次访问该二叉树(每一层将单独输出一行),每一层要求访问的顺序为从左到右
104
105 cout << "输出二叉树某一层结点(从左到右)" << endl;
106 PrintNodeAtLevel(T,1); //输出二叉树某一层结点(从左到右)
107 cout << endl;
108
109 cout << "输出二叉树第m(m=1)层的第k(k=1)个节点值" << endl;
110 mLevelKnode(T,1,&cnt);
111 cout << endl;
112
113 return 0;
114 }

posted on 2011-11-29 20:34  LoveFM  阅读(233)  评论(0编辑  收藏  举报