C++ recursive solution


  • 0
    J
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* addOneRow(TreeNode* root, int v, int d) {
            int depth = 1;
            if(d==1)
            {
                 TreeNode *newNode = new TreeNode(v);
                 newNode->left = root;
                 return newNode;
            }
            return dfs(root,depth,v,d);
        }
        TreeNode* dfs(TreeNode*root,int depth,int v,int d)
        {
            if(!root) return NULL;
            if(depth ==d-1)
            {
                TreeNode *newNode = new TreeNode(v);
                TreeNode*left = root->left;
                root->left = newNode;
                newNode->left = left;
                
                TreeNode *newNode2 = new TreeNode(v);
                TreeNode*right = root->right;
                root->right = newNode2;
                newNode2->right = right;
                
                return root;
            }
            root->left = dfs(root->left,depth+1,v,d);
            root->right = dfs(root->right,depth+1,v,d);
            return root;
        }
    };
    

Log in to reply
 

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