Share my C++ space O(1) using recursive metch


  • 0
    X
    /**
     * 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* myDFS(TreeNode *root, TreeNode *pre){
    		if(root==NULL) return NULL;
    		TreeNode *lnode=root->left;
    		TreeNode *rnode=root->right;
    
    		if(pre!=NULL){
    			pre->right=root;
    			pre->left=NULL;
    		}
    
    		TreeNode *node=root;
    		if(lnode!=NULL){node=myDFS(lnode, root);}
    		if(rnode!=NULL){node=myDFS(rnode, node);}
    
    		return node;
    	}
    	
        void flatten(TreeNode* root) {
    		TreeNode *pre=NULL;
    		myDFS(root,pre);
    		
            
        }
    };

Log in to reply
 

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