Java Recursive Rolution


  • 0
    Z

    The basic idea is at every node A, get arraylist Aleft and Aright, merge them into one by comparing Aleft[i] and Aright[i]. Then add A.val to the first of the arraylist. By this we can guarantee that Aleft[i] and Aright[i] are always at the same level.

    public List<Integer> largestValues(TreeNode root) {
            if(root==null){
                return new ArrayList<>();
            }
            if(root.left == null & root.right==null){
                List<Integer> branch= new ArrayList<>();
                branch.add(root.val);
                return branch;
            }
            else{
                List<Integer> branch1 = largestValues(root.left);
                List<Integer> branch2 = largestValues(root.right);
    
    // here just to save the space, I reuse the branch1 or branch2 instead of making a new arraylist 
                if(branch1.size()>branch2.size()){
                    for(int i = 0;i<branch2.size();i++){
                        branch1.set(i,Math.max(branch1.get(i),branch2.get(i)));
                    }
                    branch1.add(0,root.val);
                    return branch1;
                }
                else{
                    for(int i = 0;i<branch1.size();i++){
                        branch2.set(i,Math.max(branch1.get(i),branch2.get(i)));
                    }
                    branch2.add(0,root.val);
                    return branch2;
                }
            }
        }
    

Log in to reply
 

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