【编程题目】输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印
第 16 题(树):
题目(微软):
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
8
/ \
6 10
/ \ / \
5 7 9 11
输出 8 6 10 5 7 9 11。
思路:之前做USACO和学算法的时候经常用的 广度优先搜索
1 /* 2 第 16 题(树): 3 题目(微软): 4 输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。 5 例如输入 6 8 7 / \ 8 6 10 9 / \ / \ 10 5 7 9 11 11 输出 8 6 10 5 7 9 11。 12 start time = 19: 10 13 end time = 19:36 14 */ 15 16 17 //思路 广度优先遍历 18 #include <iostream> 19 #include <queue> 20 #include <stdlib.h> 21 using namespace std; 22 23 typedef struct BSTreeNode 24 { 25 int m_nValue; // value of node 26 BSTreeNode *m_pLeft; // left child of node 27 BSTreeNode *m_pRight; // right child of node 28 }BSTreeNode; 29 30 int addBSTreeNode(BSTreeNode * &T, int data) //把data加入的以T为根的树中 31 { 32 if(T == NULL) //根节点单独处理 33 { 34 T = (BSTreeNode *)malloc(sizeof(BSTreeNode)); 35 T->m_nValue = data; 36 T->m_pLeft = NULL; 37 T->m_pRight = NULL; 38 } 39 else 40 { 41 BSTreeNode * x = T; 42 BSTreeNode * px = NULL; 43 while(x != NULL) 44 { 45 if(data >= x->m_nValue) 46 { 47 px = x; 48 x = x->m_pRight; 49 } 50 else 51 { 52 px = x; 53 x = x->m_pLeft; 54 } 55 } 56 57 if(data >= px->m_nValue) 58 { 59 px->m_pRight = (BSTreeNode *)malloc(sizeof(BSTreeNode)); 60 px->m_pRight->m_nValue = data; 61 px->m_pRight->m_pLeft = NULL; 62 px->m_pRight->m_pRight = NULL; 63 } 64 else 65 { 66 px->m_pLeft = (BSTreeNode *)malloc(sizeof(BSTreeNode)); 67 px->m_pLeft->m_nValue = data; 68 px->m_pLeft->m_pLeft = NULL; 69 px->m_pLeft->m_pRight = NULL; 70 } 71 } 72 return 1; 73 } 74 75 int BFSPrintTree(BSTreeNode * T) 76 { 77 queue<BSTreeNode *> Q; 78 Q.push(T); 79 80 while(!Q.empty()) 81 { 82 BSTreeNode * x = Q.front(); 83 Q.pop(); 84 printf("%d ", x->m_nValue); 85 if(x->m_pLeft != NULL) 86 { 87 Q.push(x->m_pLeft); 88 } 89 if(x->m_pRight != NULL) 90 { 91 Q.push(x->m_pRight); 92 } 93 94 } 95 return 1; 96 } 97 98 int main() 99 { 100 BSTreeNode * T = NULL; 101 addBSTreeNode(T, 8); 102 addBSTreeNode(T, 6); 103 addBSTreeNode(T, 10); 104 addBSTreeNode(T, 5); 105 addBSTreeNode(T, 7); 106 addBSTreeNode(T, 9); 107 addBSTreeNode(T, 11); 108 109 BFSPrintTree(T); 110 return 0; 111 112 }