404. Sum of Left Leaves(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83096133

题目:

Find the sum of all left leaves in a given binary tree.
Example:

    3    
   / \   
  9  20
    /  \   
   15   7
There are two left leaves in the binary tree, with values 9 and 15 respectively. 
Return 24.

解释:
求所有左边叶子结点的和。
python代码:

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

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root==None:
            return 0
        result=0
        if root.left!=None:
            if root.left.left==None and root.left.right==None:
                result+=root.left.val
            else:
                result+=self.sumOfLeftLeaves(root.left)
        result+=self.sumOfLeftLeaves(root.right)
        return result

c++代码:

/**
 * 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) {
        int result=0;
        if (!root)
        {
            return 0;
        }
        if (root->left)
        {
            if (root->left->left==NULL && root->left->right==NULL)
            {
                result+=root->left->val;
            }      
            else
                result+=sumOfLeftLeaves(root->left);
        }
        result+=sumOfLeftLeaves(root->right);
        return result;
    } 
};

总结:
看到树的问题还是用递归。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83096133