Skip to content

Latest commit

 

History

History
110 lines (94 loc) · 2.51 KB

404.-sum-of-left-leaves.md

File metadata and controls

110 lines (94 loc) · 2.51 KB

404. Sum of Left Leaves

{% tabs %} {% tab title="Go" %}

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumOfLeftLeaves(root *TreeNode) int {
    if root == nil{
        return 0
    }
    sum := 0
    if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
        sum += root.Left.Val
    }
    return sum + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}

{% endtab %}

{% tab title="CPP" %}

**
 * 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:
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == nullptr) return 0; 
        int sum = 0;
        if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
            sum += root->left->val;
        }
        return sum + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};

{% endtab %}

{% tab title="Python 简化" %}

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:


        ##还是那个想要想明白什么是左子树

        if not root:
            return 0
        val = 0 
        ## 这个node存在,并且它是光棍
        if root.left and not root.left.left and not root.left.right:
            val += root.left.val

        return val + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

{% endtab %}

{% tab title="Python" %}

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        # 这题的难点就是如何判断左边的子树
        #
        return self.dfs(root)
        
        
        
    def dfs(self, root): # return value
        
        sum = 0
        if not root:
            return 0
        ## root
        if root.left and not root.left.left and not root.left.right:
            sum += root.left.val
        ## left and right
        
        sum += self.dfs(root.left) + self.dfs(root.right)
            
        return sum

{% endtab %} {% endtabs %}