LeetCode 404. 左叶子之和 树遍历

地址 https://leetcode-cn.com/problems/sum-of-left-leaves/

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 915,所以返回 24

算法1
主要是树的遍历要熟悉 ,然后加上判断是否是叶子和左节点

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 ans = 0;

    void dfs(TreeNode* root,int isLeft){
        if(root==NULL) return;

        if(root->left==NULL && root->right == NULL && isLeft){
            ans += root->val; return;
        }

        dfs(root->left,1);
        dfs(root->right,0); 
    }

    int sumOfLeftLeaves(TreeNode* root) {
        if(root == NULL)  return 0;
        dfs(root,0);
        return ans;
    }
};

 

posted on 2020-09-19 10:11  itdef  阅读(118)  评论(0编辑  收藏  举报

导航