My answer in C++, is there any other answers?


  • -9
    O

    class Solution {
    public:
    vector<vector<int> > levelOrder(TreeNode *root) {
    vector<vector<int> > resv;//return
    if (root==NULL)
    {
    return resv;
    }
    queue<TreeNode *> q;
    q.push(root);
    int countInLevel=1;//node count in every level
    int tmpCount=0;//for temp count in child level
    TreeNode *p;
    while (!q.empty())
    {
    vector<int> v;
    while (countInLevel--)
    {
    p=q.front();
    v.push_back(p->val);
    q.pop();
    if (p->left)
    {
    q.push(p->left);
    tmpCount++;
    }
    if (p->right)
    {
    q.push(p->right);
    tmpCount++;
    }
    }
    countInLevel=tmpCount;//fresh
    tmpCount=0;//fresh
    resv.push_back(v);
    }
    return resv;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.