Brute force solution using Java, O(nlogk), where n is the node counts, and k is the depth.


  • 0

    Straight forward: pop the leaves and put them in a list, and do it recursively.

    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> leavesList = new ArrayList<List<Integer>>();
            if(root == null) 
                return leavesList;
            while(root.left != null || root.right != null) {
                List<Integer> l = new ArrayList<Integer>();
                popNode(root, l);
                leavesList.add(l);
            }
            List<Integer> l = new ArrayList<Integer>();
            l.add(root.val);
            leavesList.add(l);
            return leavesList;
        }
        
        private void popNode(TreeNode root, List<Integer> l){
            if(root.left != null) {
                if(root.left.left == null && root.left.right == null) {
                    l.add(root.left.val);
                    root.left = null;
                } else
                    popNode(root.left, l);
            } 
            if(root.right != null) {
                if(root.right.left == null && root.right.right == null) {
                    l.add(root.right.val);
                    root.right = null;
                } else            
                    popNode(root.right, l);  
            } 
        }
    }
    

Log in to reply
 

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