Flashcards
Binary Tree Level Order Traversal
Cards in this deck (1)
- 1Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], [ [3], [9,20], [15,7] ]public List> levelOrder(TreeNode root) {
List> mainList = new ArrayList>();
if(root == null) return mainList;
Queue q = new LinkedList();
q.add(root);
while(!q.isEmpty()){
int count = q.size();
List subList = new ArrayList();
for(int i = 0 ;i< count; i++){
TreeNode node = q.peek();
if(node.left!=null) q.add(node.left);
if(node.right!=null) q.add(node.right);
subList.add(q.poll().val);
}
mainList.add(subList);
}
return mainList;
}
Information
- Description
- Flashcards on Binary Tree Level Order Traversal, created by Suhas S on 11/04/2018.
- Created by
- Suhas S
- Views
- 0
- Rating