首页 > 其他分享 >代码随想录:左叶子之和

代码随想录:左叶子之和

时间:2025-01-12 20:45:03浏览次数:1  
标签:node right TreeNode val int 代码 随想录 叶子 left

代码随想录:左叶子之和

没啥意思,很铸币的判断方法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) { return tra(root); }

    int tra(TreeNode* node) {
        if (!node)
            return 0;

        int sum = 0;
        if (node->left) {
            if (node->left->left == NULL && node->left->right == NULL) {
                sum += node->left->val;
            } else {
                sum += tra(node->left);
            }
        }
        if (node->right) {
            sum += tra(node->right);
        }
        return sum;
    }
};

标签:node,right,TreeNode,val,int,代码,随想录,叶子,left
From: https://www.cnblogs.com/huigugu/p/18667252

相关文章