My simple C++ solution, very few code, easy understand


  • 0
    Z

    Go down by each node's left child node from root, use recursion of each node's right child node and return their sum of left leaves. To make it easier to begin, I add a virtual node, point its right to root

    int sumOfLeftLeaves(TreeNode* root) {
        
        if (!root) return 0;
        
        TreeNode f(0);
        f.right = root;//make a virtual root so that the function can go down
        
        int ret = helper(f.right, &f);
        return ret;
    }
    
    int helper(TreeNode * root, TreeNode * parent) {
        if (!root) return 0;
        
        int ret = 0;
        
        while (root) {
            ret += helper(root->right, root);
            if (root != parent->right && !root->left && !root->right) ret += root->val;// if the node is leaf, check if it is the parent's right child
            root = root->left;
        }
        return ret;
    }

Log in to reply
 

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