366. Find Leaves of Binary Tree

Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Given binary tree

          1
         / \
        2   3
       / \     
      4   5    

Returns [4, 5, 3], [2], [1].

Solution1:遞歸 Post-order Divide&Conquer Bottom-up向上傳遞

思路: ?Divide 左右樹,Conquer求出距l(xiāng)eaf最大距離max_dist 并將其向上傳遞,對(duì)應(yīng)添加到result_list
1a寫法先求出了height,建好了固定長度的結(jié)果。
但其實(shí)不用,其實(shí)根據(jù)遍歷順序發(fā)現(xiàn)最大距離是若增一定連續(xù),所以不用提前建好result_list,每次超過后動(dòng)態(tài)增加即可,如寫法2a。
Time Complexity: O(N) Space Complexity: O(N) 遞歸緩存

Solution1a Code:

class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        // build result list
        int height = getMaxHeight(root);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        for(int i = 0; i < height; i++) result.add(new ArrayList<Integer>());
        
        // bottom-up dfs
        dfsHelper(result, root);
        return result;
    }
    private int dfsHelper(List<List<Integer>> result, TreeNode node) {
        if(node == null) return -1;
            
        int max_dist = 1 + Math.max(dfsHelper(result, node.left), dfsHelper(result, node.right));
        result.get(max_dist).add(node.val);
        
        return max_dist;
    }
    
    private int getMaxHeight(TreeNode root) {
        if(root == null) return 0;
        return 1 + Math.max(getMaxHeight(root.left), getMaxHeight(root.right));
    }
}

Solution2a Code:

class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null) return result;
        dfs(root, result);
        return result;
    }
    private int dfs(TreeNode node, List<List<Integer>> result) {
        if(node == null) return 0;
        int left_d = dfs(node.left, result);
        int right_d = dfs(node.right, result);
        
        int level = Math.max(left_d, right_d) + 1;
        if(level > result.size()) result.add(new ArrayList<>());
        
        result.get(level - 1).add(node.val);
        return level;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容