Java Solution Recursive


  • 0
    J
    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            if(root==null) return new ArrayList<List<Integer>> ();
            
            List<List<Integer>> left = findLeaves(root.left);
            List<List<Integer>> right = findLeaves(root.right);
            
            List<Integer> list = new ArrayList<> ();
            list.add(root.val);
            
            if(left.size()==0 || right.size()==0){
                List tar = left.size()!=0?left:right;
                tar.add(list);
                return tar;
            } else {
                int i=0;
                while(i<left.size() && i<right.size()){
                    List<Integer> cur = left.get(i);
                    cur.addAll(right.get(i++));
                }
                while(i<right.size()){
                    left.add(right.get(i++));
                }
                left.add(list);
                return left;
            }
        }
    }
    

Log in to reply
 

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