Sum of Left Leaves - LintCode

描述
Find the sum of all left leaves in a given binary tree.

樣例

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

思路
處理結點有左子樹,且左子樹是葉子結點的情況

#ifndef C1254_H
#define C1254_H
#include<iostream>
using namespace std;
class TreeNode{
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val){
        this->val = val;
        this->left = this->right = NULL;
    }
};
class Solution {
public:
    /**
    * @param root: t
    * @return: the sum of all left leaves
    */
    int sumOfLeftLeaves(TreeNode * root) {
        // Write your code here
        if (!root)
            return 0;
        //處理結點有左子樹,且左子樹是葉子結點的情況
        if (root->left&&!root->left->left&&!root->left->right)
        {
            sum += root->left->val;
        }
        sumOfLeftLeaves(root->left);
        sumOfLeftLeaves(root->right);
        return sum;
    }
    int sum = 0;
};
#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章