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

404 Sum of Left Leaves 左葉子之和

AR tree etc 二叉 ble roo bsp true desc

計算給定二叉樹的所有左葉子之和。
示例:
3
/ \
9 20
/ \
15 7
在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24。

詳見:https://leetcode.com/problems/sum-of-left-leaves/description/

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) {
        if(!root||!root->left&&!root->right)
        {
            return 0;
        }
        int res=0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty())
        {
            root=que.front();
            que.pop();
            if(root->left&&!root->left->left&&!root->left->right)
            {
                res+=root->left->val;
            }
            if(root->left)
            {
                que.push(root->left);
            }
            if(root->right)
            {
                que.push(root->right);
            }
        }
        return res;
    }
};

方法二:

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

參考:https://www.cnblogs.com/grandyang/p/5923559.html

404 Sum of Left Leaves 左葉子之和