C++ simple and fast O(n) solution

  • 0
    TreeNode* addOneRow(TreeNode* root, int v, int d) {
            if(d==1) {
                TreeNode* r=new TreeNode(v);
                return r;
            DFS(root, 1, v, d);
            return root;
        void DFS(TreeNode* r, int dep, int v, int d) {
            if(r==NULL) return;
            if(dep==d-1) {
                TreeNode* l=r->left;
                TreeNode* ri=r->right;
                r->left=new TreeNode(v), r->right=new TreeNode(v);
                r->left->left=l, r->right->right=ri;
            DFS(r->left, dep+1, v, d);
            DFS(r->right, dep+1, v, d);

Log in to reply

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