LeetCode 0404 Sum of Left Leaves【左边叶节点数量,二叉树,递归】

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.

题意

思路1

  • 左边结点存在,左边结点是叶子结点
  • 递归左右子树求和

代码1

/**
 * 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 == NULL) return 0;
        // 左结点存在
        if(root->left)
        {
            // 左节点是叶子结点
            if(root->left->left == NULL && root->left->right == NULL)
                return root->left->val + sumOfLeftLeaves(root->right);
        }
        return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};
原创文章 193 获赞 27 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/105748789