Problem:
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,null,null,15,7]
,
3
/
9 20
/
5 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
思路:
Solution (C++):
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
levelOrder(root, res, 0);
return res;
}
private:
void levelOrder(TreeNode* root, vector<vector<int>> &res, int depth) {
if (!root) return;
if (res.size() == depth) res.push_back(vector<int>());
res[depth].push_back(root->val);
levelOrder(root->left, res, depth+1);
levelOrder(root->right, res, depth+1);
}
性能:
Runtime: 8 ms Memory Usage: 14.8 MB