LeetCode:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
/**
* 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:
int TreeHeight(TreeNode* root)
{
if(!root)
return 0;
int lefth = TreeHeight(root->left);
int righth = TreeHeight(root->right);
return lefth > righth ? lefth + 1 : righth + 1;
}
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> nodeq;
queue<int> levelq;
vector<vector<int>> v;
if(root)
{
nodeq.push(root);
levelq.push(1);
}
v.resize(TreeHeight(root));
while(!nodeq.empty())
{
TreeNode* node = nodeq.front();
nodeq.pop();
int level = levelq.front();
levelq.pop();
v[level - 1].push_back(node->val);
if(node->left)
{
nodeq.push(node->left);
levelq.push(level+1);
}
if(node->right)
{
nodeq.push(node->right);
levelq.push(level+1);
}
}
return v;
}
};