C++ DFS Solution


  • 0
    Y
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            int ans = 0;
            dfs(root, ans);
            return ans;
        }
    private:
        void dfs(TreeNode* root, int &ans){
            if(root == NULL)
                return ;
            if(root->left != NULL){
                TreeNode* tmp = root->left;
                if(tmp->left == NULL && tmp->right == NULL){
                    ans += tmp->val;
                }else
                    dfs(root->left, ans);
            }
            if(root->right)
                dfs(root->right, ans);
        }
    };
    

Log in to reply
 

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