leetcode 404. 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,右节点标2,那么当遍历到叶子节点的时候,我们只加标记为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 ans = 0;
    void dfs(TreeNode* root, int mark) {
        if (root == nullptr) return;
        if (root->left == nullptr && root->right == nullptr) {
            if (mark == 1)ans += root->val;
            //return ;
        }
        dfs(root->left, 1);
        dfs(root->right, 2);
    }
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == nullptr) return 0;
        dfs(root, 0);
        return ans;
    }
};
posted on 2018-02-28 19:39  Beserious  阅读(50)  评论(0编辑  收藏  举报