求二叉樹的所有末級左節點的值的和

題目:Sum of Leaves

描述:

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.

翻譯:

這兒有2個末級左子節點,值分別爲9和15,它們的和是24

答案:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        int sum = 0;
        if (root == null)
            return sum;
        TreeNode node = root.left;
        if (node != null) {
            if (node.left == null && node.right == null)
                sum += node.val;
            else
                sum += sumOfLeftLeaves(node);
        }
        sum += sumOfLeftLeaves(root.right);
        return sum;
    }
}

算法說明:

利用遞歸,將末級左節點找到,並將值累加

發佈了54 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章