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].

Explanation:

  1. Removing the leaves [4, 5, 3] would result in this tree:
    1
    /
    2

  2. Now removing the leaf [2] would result in this tree:
    1

  3. Now removing the leaf [1] would result in the empty tree:

       []         
    

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

一刷
題解:利用level信息,這個level指的是從下到上的高度。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        height(root, res);
        return res;
    }
    
    private int height(TreeNode node, List<List<Integer>> res){
        if(node == null) return -1;
        int level = 1 + Math.max(height(node.left, res), height(node.right, res));
        while(res.size()<level+1) res.add(new ArrayList<>());
        res.get(level).add(node.val);
        return level;
    }
}

二刷
思路同上

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        height(root, res);
        return res;
    }
    
    private int height(TreeNode root, List<List<Integer>> res){
        if(root == null) return -1;
        int level = 1 + Math.max(height(root.left, res), height(root.right, res));
        if(level+1>res.size()){
            res.add(new ArrayList<>());
        }
        res.get(level).add(root.val);
        return level;
    }
}

三刷
根據(jù)節(jié)點的高度信息,取出對應(yīng)層次的list, 并add新的val

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

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