DFS with list / T: O(N), S:O(N)


  • 0
    J
    public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> lst = new ArrayList<List<Integer>>();
            dfs(lst, root);
            return lst;
        }
        
        public int dfs(List<List<Integer>> lst, TreeNode root){
            if(root == null)
                return -1;
            
            int left = dfs(lst, root.left);
            int right = dfs(lst, root.right);
            int index = ((left < right) ? right : left) + 1;
            
            if(index >= lst.size()){
                lst.add(new ArrayList<Integer>());
            }
            lst.get(index).add(root.val);
            return index;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.