Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 12, 2017 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/5484389ddb19f76eac5ee9e32ceb376f to your computer and use it in GitHub Desktop.
Save InterviewBytes/5484389ddb19f76eac5ee9e32ceb376f to your computer and use it in GitHub Desktop.
Largest values.. each level. Binary tree
package com.interviewbytes.trees;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class LargestValues {
public List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
if (root != null) queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
while (size > 0) {
TreeNode node = queue.poll();
max = Math.max(max, node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
size--;
}
list.add(max);
}
return list;
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment