C++ Level Order


  • 0
    F

    Traverse down to level d-1, and add one row to it.

    class Solution {
    public:
        TreeNode* addOneRow(TreeNode* root, int v, int d) {
            if (d == 1) {
                TreeNode *n = new TreeNode(v);
                n->left = root;
                return n;
            }
            
            int depth = 1;
            queue<TreeNode *> q;
            q.push(root);
            while (depth < d-1) {
                int siz = q.size();
                while (siz > 0) {
                    TreeNode *curr = q.front();
                    q.pop();
                    siz--;
                    if (curr->left) q.push(curr->left);
                    if (curr->right) q.push(curr->right);
                }
                depth++;
            }
            while (!q.empty()) {
                TreeNode *curr = q.front();
                q.pop();
                TreeNode *left = curr->left, *right = curr->right;
                curr->left = new TreeNode(v);
                curr->right = new TreeNode(v);
                curr->left->left = left;
                curr->right->right = right;
            }
            return root;
        }
    };
    

Log in to reply
 

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