题目:Binay Tree Level Order Traversal
代码语言:javascript复制Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
如下一棵树
转换之后需要输出这样的形式:
如下,见代码:
代码语言:javascript复制 1 struct TreeNode {
2 int val;
3 TreeNode* left;
4 TreeNode* right;
5 TreeNode():val(0),left(NULL),right(NULL) {}
6 TreeNode(int x): val(x), left(NULL),right(NULL) {}
7 };
8
9
10 vector<vector<int> > levelOrderTraversal(TreeNode *root) //非递归的中序遍历(用栈实现)
11 {
12
13 queue<TreeNode *> tree_queue;
14 vector<vector<int> > tree_vector;
15 vector<int> svector;
16
17 if (NULL == root) {
18 return tree_vector;
19 }
20 TreeNode *pTemp = root;
21 tree_queue.push(root);
22 tree_queue.push(NULL); //the end of one level.
23
24 while (true) {
25 TreeNode *pTemp = tree_queue.front();
26 tree_queue.pop();
27
28 if (!pTemp) { //get the null, put vector<> to vector<vector<>>
29 tree_vector.push_back(svector);
30 svector.clear();
31 if (tree_queue.empty())
32 break;
33 tree_queue.push(NULL);
34 }
35 else {
36 svector.push_back(pTemp->val);
37 if (pTemp->left)
38 tree_queue.push(pTemp->left);
39 if (pTemp->right)
40 tree_queue.push(pTemp->right);
41 }
42 }
43 return tree_vector;
44 }