[623. Add One Row to Tree] C++_Using Queue_AC


  • 0
    class Solution {
    public:
    TreeNode* addOneRow(TreeNode* root, int v, int d) {
        if(d == 1){
            TreeNode* neoRoot = new TreeNode(v);
            neoRoot->left = root;
            root = neoRoot;
        }else{
            queue<TreeNode*> q;
            q.push(root);
            queue<TreeNode*> pre_q;
            while(!q.empty() && d > 1){
                queue<TreeNode*> tmp_q;
                pre_q = tmp_q;
                int len = q.size();
                while(len){
                    TreeNode* node = q.front();
                    if(node->left) q.push(node->left);
                    if(node->right) q.push(node->right);
                    q.pop();
                    pre_q.push(node);
                    len--;
                }
                d--;
            }
            while(!pre_q.empty()){
                TreeNode* node = pre_q.front();
                TreeNode* nl = node->left;
                TreeNode* nr = node->right;
                node->left = new TreeNode(v);
                node->left->left = nl;
                node->right = new TreeNode(v);
                node->right->right = nr;
                pre_q.pop();
            }
        }
        return root;
    }
    };

Log in to reply
 

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