Find Leaves of Binary Tree

来源:互联网 发布:西昊 ergomax 知乎 编辑:程序博客网 时间:2024/05/01 23:46

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

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

思路:就是一个层级关系;计算每一层的depth,然后往上返回的应该是 Math.max(leftdepth, rightdepth)+1; 如果lists.size()< curdepth,证明需要继续加list;

/** * 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>> lists = new ArrayList<List<Integer>>();        if(root == null) return lists;        collect(root, lists);        return lists;    }        public int collect(TreeNode root, List<List<Integer>> lists){        if(root == null) return 0;        int leftdepth = collect(root.left, lists);        int rightdepth = collect(root.right, lists);        int curdepth = Math.max(leftdepth, rightdepth)+1;        if(lists.size() < curdepth){            List<Integer> list = new ArrayList<Integer>();            list.add(root.val);            lists.add(list);        } else {            lists.get(curdepth-1).add(root.val);        }        return curdepth;    }}


0 0
原创粉丝点击