42 Deepest Leaves Sum

題目

Given a binary tree, return the sum of values of its deepest leaves.
在這裏插入圖片描述
Constraints:

The number of nodes in the tree is between 1 and 10^4.
The value of nodes is between 1 and 100.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

分析

題意:求出最高層的葉子之和(按圖來說,這個最高層應當是同層唯一的,而非某一支的葉子,比如此處5沒有被算進去)。

由於不同的葉子,可能在不同的層次,因此我們得記錄葉子所在層次。
一開始想到使用map存儲,但是key和value(對應層數和葉子值)都不能保證唯一,因此突然想到好像使用數組就行。

算法:

數組的下標表示當前層數;
遍歷的每個值,都累加到當前數組arr[i]中;
返回arr[i](i爲max值)即可。

由於是遞歸,每層遞歸都要用到i作爲層數,因此我們要構造一個輔助函數,把i作爲參數傳遞下去;注意不能定義一個全局i。因爲遞歸實際上有兩個分支(左子樹和右子樹),如果用全局i,會導致左子樹i++,右子樹也i++,此時層數對應不上。

解答

class Solution {
    int[] tmp = new int[101];
    public int deepestLeavesSum(TreeNode root) {
    	// 初始化的層數i=0
        int[] res = helper(root,0);
        // 從後往前遍歷,數組默認值爲0,如果非零,就是我們要的最頂層結果
        for(int i=100;i>=0;--i)
            if (res[i]!=0)
                return res[i];
        return 0;
    }
    int[] helper(TreeNode root,int i){
        if(root==null) return null;
        // 將當前值加到數組中,然後層數加1
        tmp[i++]+=root.val;
        helper(root.left,i);
        helper(root.right,i);
        return tmp;
    }
}

我看了下評論區的答案,我的算法竟然是最快的,也是最簡潔的。
在這裏插入圖片描述
這是評論區同複雜度的其他解法;

class Solution {
    public int deepestLeavesSum(TreeNode root) {
        int[] maxDepth = new int[1];
        int[] sumOfDeepestLeaves = new int[1];
        findDepth(root, maxDepth, sumOfDeepestLeaves, 1);
        return sumOfDeepestLeaves[0];
    }
    
    public void findDepth(TreeNode root, int[] maxDepth, int[] sumOfDeepestLeaves, 
                          int currDepth) {
        if(root == null) {
           return; 
        }
        
        if(root.left == null && root.right == null) {
            /** If depth of the current leaf is equal to existing maximum depth, 
                add the value of this leaf to the existing sum of deepest leaves. */
            if(maxDepth[0] == currDepth) {
                sumOfDeepestLeaves[0] += root.val;
                return;
            /** If depth of the current leaf is less than the existing maximum depth,
                dont change the existing sum of deepest leaves and return. */
            } else if(currDepth < maxDepth[0]) {
                return;
            /** If depth of the current leaf is greater than the existing maximum depth,
                set max depth to current depth and also initialize the sum of deepest leaves
                as the current node val */
            } else {
                sumOfDeepestLeaves[0] = root.val;
                maxDepth[0] = currDepth;
                return;
            }
        }
        
        findDepth(root.left, maxDepth, sumOfDeepestLeaves, currDepth+1);
        findDepth(root.right, maxDepth, sumOfDeepestLeaves, currDepth+1);
        return;
    } 
}

好像有點收穫?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章