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}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? > rea
使用队列,作FIFO。
在每一层的末尾,插入一个空指针,作为该层结束符。
在leetcode上实际执行时间为11ms。
/**
* Definition for a binary tree node.
* 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> > ans;
if (!root) return ans;
queue<TreeNode *> q;
q.push(root);
q.push(0);
ans.push_back(vector<int> ());
while (!q.empty()) {
root = q.front();
q.pop();
if (!root) {
ans.push_back(vector<int> ());
if (q.empty())
break;
q.push(0);
}
else {
ans.back().push_back(root->val);
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
}
ans.pop_back();
return ans;
}
};
算法二,深度优先递归遍历
在leetcode上实行际时间为13ms。 比上面的算法慢2ms。但是代码简洁一些。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> >ans;
helper(ans, root, 0);
return ans;
}
void helper(vector<vector<int> > &ans, TreeNode *root, int level) {
if (!root) return;
if (level == ans.size())
ans.push_back(vector<int> ());
ans[level].push_back(root->val);
helper(ans, root->left, level+1);
helper(ans, root->right, level+1);
}
};