C++ Solution


  • 0
    L
    class Solution {
    public:
        TreeNode* addOneRow(TreeNode* root, int v, int d) {
        	if(d == 1)
        	{
        		TreeNode *newRoot = new TreeNode(v);
        		newRoot->left = root;
        		return newRoot;
        	}
        	helpAddOneRow(root,v,d,1);
        	return root;
        }
    
        void helpAddOneRow(TreeNode* node, int v, int d, int currentDepth) 
        {
            if(currentDepth == d-1)
            {
            	TreeNode *newLeft = new TreeNode(v);
            	TreeNode *newRight = new TreeNode(v);
            	newLeft->left = node->left;
            	newRight->right = node->right;
            	node->left = newLeft;
            	node->right = newRight;
            }
    	else
    	{
    		if(node->left)
    			helpAddOneRow(node->left,v,d,currentDepth+1);
    		if(node->right)
    			helpAddOneRow(node->right,v,d,currentDepth+1);
    	}
        }
    };
    

Log in to reply
 

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