easy understand c++solution use two queue


  • 0
    K

    vector<vector<int>> res(1200);
    if (!root)
    return res;
    queue<TreeNode
    > q;
    queue<int>h;
    int height = 0;
    q.push(root);
    h.push(height);
    while (!q.empty()&&!h.empty()){
    TreeNode
    t = q.front();
    int k = h.front();
    q.pop();
    h.pop();
    res[k].push_back(t->val);
    if (t->left){
    q.push(t->left);
    h.push(k + 1);
    }
    if (t->right){
    q.push(t->right);
    h.push(k + 1);
    }
    }
    for (int i = 0; i < res.size(); i++){
    if (res[i].size() == 0)
    res.erase(res.begin() + i, res.end());
    }
    return res;**


Log in to reply
 

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