广搜的时候每一层加一个NULL节点俨然已经成了我的习惯……
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>> res;
if (root == NULL)
return res;
deque<TreeNode *> d;
d.push_back(root);
d.push_back(NULL);
while (!d.empty()) {
vector<int> tmp;
while (d.front() != NULL) {
TreeNode *t = d.front();
d.pop_front();
tmp.push_back(t->val);
if (t->left != NULL)
d.push_back(t->left);
if (t->right != NULL)
d.push_back(t->right);
}
d.pop_front();
if (!d.empty())
d.push_back(NULL);
res.push_back(tmp);
}
return res;
}
};
http://oj.leetcode.com/problems/binary-tree-level-order-traversal/