C++ recursive


  • 0
    B
    /**
     * 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) {
            if(d == 1)
            {
                TreeNode* node = new TreeNode(v);
                node -> left = root;
                return node;
            }
            addOneRow(root, true, v, d-1);
            addOneRow(root, false, v, d-1);
            return root;
        }
        
        void addOneRow(TreeNode* root, bool left, int v, int d)
        {
            if(!root) return;
            if(d == 1)
            {
                TreeNode* node = new TreeNode(v);
                if(left)
                {
                    node -> left = root -> left;
                    root -> left = node;
                }
                else
                {
                    node -> right = root -> right;
                    root -> right = node;
                }
            }
            else
            {
                auto child = root -> right;
                if(left) child = root -> left;
                addOneRow(child, true, v, d-1);
                addOneRow(child, false, v, d-1);
                
            }
        }
    };

Log in to reply
 

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