[LeetCode 解題筆記] Sum of Left Leaves

原題目網址: 404. Sum of Left Leaves

題目描述

給定一棵 Binary Tree,加總所有 left leaves 的值。

解題思路

想法:Tree Traversal 的過程順便作加總。

以下為用 C 語言實作的程式碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

void traversal_and_sum_left_leaves(struct TreeNode* root, bool isLeft, int *sum) {
  if (root == NULL) {
    return;
  }
  if (root->left == NULL && root->right == NULL && isLeft) {
    *sum += root->val;
  }
  traversal_and_sum_left_leaves(root->left, true, sum);
  traversal_and_sum_left_leaves(root->right, false, sum);
}

int sumOfLeftLeaves(struct TreeNode* root){
  if (root == NULL) {
    return 0;
  }
  int sum = 0;
  traversal_and_sum_left_leaves(root, false, &sum);
  return sum;
}
Show Comments