LeetCode #404 - Sum of Left Leaves - Easy

Problem

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.

Algorithm

整理一下題意:給定一棵二叉樹,求最左邊節點之和。

考慮三種情況。

  • 若根節點爲NULL,則返回0
  • 若左子節點爲空但是右子不爲空,則求和轉移到右子數
  • 若左子和左子均非空,則返回左子和右子的遞歸調用

於是可以得到遞歸方法的解。

代碼如下。

//遞歸版本,用時3ms
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root) return 0;
        if (root->left && !root->left->left && !root->left->right) {
            return root->left->val + sumOfLeftLeaves(root->right);
        }
        return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};

同樣的思路,也可以非遞歸地實現。通過層次遍歷,將所有層次最左節點加入到和中。注意while中的三個if覆蓋了遞歸版本的三種情況。

代碼如下。

//非遞歸版本,用時6ms
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root==NULL||root->left==NULL&&root->right==NULL) return 0;
        TreeNode* p;
        int sum=0;
        queue<TreeNode*> q;
        queue<TreeNode*> level;
        q.push(root);
        while(!q.empty()){
            p=q.front();
            q.pop();
            if(p->left!=NULL&&p->left->left==NULL&&p->left->right==NULL) sum+=p->left->val;
            if(p->left!=NULL) q.push(p->left);
            if(p->right!=NULL) q.push(p->right);
        }
        return sum;
    }
};
發佈了63 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章