java BFS solution


  • 0
    R

    Key:Level traversal
    Using a list keeping track of the max value of each level.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void help(TreeNode root,int level,List<Integer> max){
            if(root==null) return;
            else{
                if(level>max.size()) max.add(root.val);
                else if(max.get(level-1)<root.val) max.set(level-1,root.val);
                help(root.left,level+1,max);
                help(root.right,level+1,max);
                }
        }
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> result=new ArrayList<Integer>();
            help(root,1,result);
            return result;
        }
    }
    

Log in to reply
 

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