1 ms easy to understand java solution


  • 0
    L

    The idea is to make the parent's left or right as null. For this we can pass a boolean variable isLeft. Set it to true when making left recursive call and set it to false when making right recursive call.

        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(root==null){
                return res;
            }
            List<Integer> leaves;
            while(root.left!=null || root.right!=null){
                leaves = new ArrayList<Integer>();
                collectLeaves(null,root,leaves,false);
                res.add(leaves);
            }
            leaves = new ArrayList<Integer>();
            leaves.add(root.val);
            res.add(leaves);
            return res;
        }
        
        void collectLeaves(TreeNode parent,TreeNode root,List<Integer> leaves,boolean isLeft){
            if(root==null){
                return;
            }
            if(root.left==null && root.right==null){
                leaves.add(root.val);
                if(isLeft){
                    parent.left=null;
                }else{
                    parent.right=null;
                }
                return;
            }
            collectLeaves(root,root.left,leaves,true);
            collectLeaves(root,root.right,leaves,false);
        
        }
    

Log in to reply
 

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