LeetCode 404. Sum of Left Leaves

404. Sum of Left Leaves

Description

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.

Solution

  • 題意即求和作爲左子樹的葉子結點的值。
  • 整體解題思想是遍歷但是不遍歷右葉子,如果當前是葉子結點,那麼一定是左葉子,那麼累和。
  • 我採用的是中序遍歷的方式,對於左子樹遍歷,可以放心大膽,因爲不會遍歷到右葉子,然後判斷當前根節點,如果是葉子那麼累和,對於右子樹遍歷,需要確認該右子樹不是葉節點才能繼續遍歷,代碼如下。
class Solution {
public:
    int rnt = 0;
    void travel(TreeNode *root)  {
        if (!root) return ;
        travel(root->left);
        if (!root->left && !root->right) rnt += root->val;
        if ((root->right) && (root->right->left || root->right->right)) travel(root->right);
    }
    int sumOfLeftLeaves(TreeNode* root) {

        if (!root || (!root->left && !root->right)) return 0;
        travel(root);
        return rnt;
    }
};
發佈了77 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章