打印二叉树某一层次的值(重点)
方法一:递归
1 void printNLevel(TreeNode *root, int n)
2 {
3 if (root == NULL)
4 {
5 return ;
6 }
7
8 if (n == 1)
9 {
10 cout << root->data << endl;
11 }
12 else
13 {
14 printNLevel(root->left, n-1);
15 printNLevel(root->right, n-1);
16 }
17 }
方法二:层次遍历
1 void TransLevel2(Node* root,int level)
2 {
3 if(root == NULL)
4 return ;
5 else
6 {
7 int count_levels,count_nodes,level_nodes;
8 Node* tmp;
9 Queue<Node*> queue;
10 queue.EnQueue(root);
11
12 count_levels=1;
13
14 while(!queue.IsEmpty())
15 {
16 if(count_levels == level)
17 break;
18
19 count_nodes = 0;
20
21 level_nodes = queue.Size();
22
23 while(count_nodes < level_nodes)
24 {
25 tmp = queue.DeQueue();
26
27 if(tmp->left != NULL)
28 queue.EnQueue(tmp->left);
29
30 if(tmp->right != NULL)
31 queue.EnQueue(tmp->right);
32
33 count_nodes++;
34 }
35
36 count_levels++;
37 }
38
39 PrintQueue(queue);
40 }
41 }