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] ]
题目很基础啊,就是给一个二叉树按照层依次输出,思路:满二叉树的子节点个数是父节点的2倍
cpp代码:
/**
* 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) {
std::vector<TreeNode*> fatherNodes; //存储父节点
std::vector<TreeNode*> childNodes; //存储子节点
std::vector<vector<int>> result; //返回容器
if(!root) return result; //空值返回
//插入根节点的值
std::vector<int> temp;
temp.push_back(root->val);
result.push_back(temp);
fatherNodes.push_back(root); //插入根节点
//循环父节点数组
for (int i = 0; i < fatherNodes.size(); i++) {
//将左右子节点插入子节点数组(NULL值也插入)
childNodes.push_back(fatherNodes[i]->left);
childNodes.push_back(fatherNodes[i]->right);
//判断是否满足满二叉树性质(子节点个数是上一次父节点个数的2倍)
if(childNodes.size() == 2 * fatherNodes.size())
{
//清空父节点数组
fatherNodes.clear();
//准备插入当前层非空子节点
std::vector<int> levelNodeValues;
for (int j = 0; j < childNodes.size(); j++) {
if(childNodes[j] != NULL)
{
levelNodeValues.push_back(childNodes[j]->val);
fatherNodes.push_back(childNodes[j]);
}
}
//清理子节点数组
childNodes.clear();
//插入容器中
if (levelNodeValues.size())
result.push_back(levelNodeValues);
//清理层节点值数组
levelNodeValues.clear();
i = -1; //重新从0开始循环
}
}
return result;
}
};