Java - use map - Straight


  • 2
    H

    [

    /**
     * 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) {
            HashMap<Integer, List<Integer>> m = new HashMap<>();
            List<List<Integer>> res = new LinkedList<>();
            int max = height(root, m);
            
            for(int i = 1; i<max; i++){
                if(m.containsKey(i))
                    res.add(m.get(i));
            }
            return res;
        }
        
        public int height(TreeNode root, HashMap<Integer, List<Integer>> m){
            if(root == null) return 0;
            int max = Math.max(height(root.left, m), height(root.right, m)) + 1;
            if(m.containsKey(max))
                m.get(max).add(root.val); 
            else{
                LinkedList<Integer> l = new LinkedList<>();
                l.add(root.val);
                m.put(max, l);
            }
            return max+1;
        }
    }
    

    ]1


Log in to reply
 

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