Bootstrap

C语言 | Leetcode C语言题解之第404题左叶子之和

题目:

题解:

bool isLeafNode(struct TreeNode *node) {
    return !node->left && !node->right;
}

int sumOfLeftLeaves(struct TreeNode *root) {
    if (!root) {
        return 0;
    }
    struct TreeNode **q = malloc(sizeof(struct TreeNode *) * 2001);
    int left = 0, right = 0;
    q[right++] = root;
    int ans = 0;
    while (left < right) {
        struct TreeNode *node = q[left++];
        if (node->left) {
            if (isLeafNode(node->left)) {
                ans += node->left->val;
            } else {
                q[right++] = node->left;
            }
        }
        if (node->right) {
            if (!isLeafNode(node->right)) {
                q[right++] = node->right;
            }
        }
    }
    return ans;
}
;