3ms_C++_Recursive_DFS


  • 0

    Simple explanation:
    Each time when we input the root, we also input the "type" of this root (Left or Not Left), so by using DFS and recursive method, we can reach to the end of each path, then we can conclude the sum of left leaves by using the information from "type".

    class Solution {
    public:
    int sumOfLeftLeaves(TreeNode* root) {
        return DFS(root,false);
    }
    
    int DFS(TreeNode* root, bool isLeft){
        if(root == NULL) return 0;
        if(!root->left && !root->right && isLeft){return root->val;}
        return DFS(root->left,true) + DFS(root->right,false);
    }
    };

Log in to reply
 

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