Easy java solution using TreeSet


  • 0
    D
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> largestValues(TreeNode root) {
            
            //variable to store the level order Traversal list
            List<TreeSet<Integer>> levelTraversal=new ArrayList<TreeSet<Integer>>();
            //variable to store the solution
            List<Integer> solution=new ArrayList<Integer>();
            
            //Base case: if root is null, return list
            if(root==null)
                return solution;
            
            //General case: if 1 or more nodes are present
            levelOrderTraversal(root,0,levelTraversal);
            
            //iterate through levelTraversal list and obtain the last element in each level(as it is sorted you will get the max element)
            for(int i=0;i<levelTraversal.size();i++)
            {
                
                solution.add(levelTraversal.get(i).last());
            }
            
            return solution;
            
            
        }
        
        public void levelOrderTraversal(TreeNode root, int level, List<TreeSet<Integer>> levelTraversal)
        {
            //Base case: if root is null, return
            if(root==null)
                return;
            
            //General case: if 1 or more nodes are present
            if(level<levelTraversal.size())
            {
                levelTraversal.get(level).add(root.val);
            }
            else
            {
                TreeSet<Integer> set=new TreeSet<Integer>();
                set.add(root.val);
                levelTraversal.add(set);
            }
            
            //iterate on left and right subtrees
            levelOrderTraversal(root.left,level+1,levelTraversal);
            levelOrderTraversal(root.right,level+1,levelTraversal);
        }
    }
    

Log in to reply
 

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