1. 程式人生 > >leetcode 404. 左葉子之和(Sum of Left Leaves)

leetcode 404. 左葉子之和(Sum of Left Leaves)

truct tco eno list left title pre amp public

目錄

  • 題目描述:
  • 示例:
  • 解法:

題目描述:

計算給定二叉樹的所有左葉子之和。

示例:

        3
       /       9  20
        /         15   7

    在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24

解法:

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

                }else{
                    res += sumOfLeftLeaves(root->right);
                }
            }   
            return res;
        }
        
    }
};

leetcode 404. 左葉子之和(Sum of Left Leaves)