3 ms Clear C++ Solution


  • 0
    L
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            return helper(root, 0);
        }
        
        // flag == 0: This is root
        // flag == 1: This is left child of parent
        // flag == 2: This is right child of parent
        int helper(TreeNode* root, int flag) {
            if (!root) {
                return 0;
            }
            if (flag == 0) {
                return helper(root -> left, 1) + helper(root -> right, 2);
            }
            if (flag == 1) {
                // This is left child of its parent and it has no children, so it's left leaf
                if (!root -> left && !root -> right) {
                    return root -> val;
                }
            }
            return helper(root -> left, 1) + helper(root -> right, 2);
        }
    };

  • 0
    K

    @lijunray It's not "clear" to me! What is the meaning of 0, 1 and 2 for the flag value?


  • 0
    L

    @kasim Sorry for the confusion. I added some comments. If it's still not clear, just reply to me. Thx!


Log in to reply
 

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