Given 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
Given binary tree
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Ans:
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> result = new LinkedList<List<Integer>>();
if(root == null) {
return result;
}
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> tempList = new LinkedList<Integer>();
for(int i=0; i<size; i++) {
TreeNode temp = queue.poll();
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
tempList.add(temp.val);
}
result.add(tempList);
}
return result;
}
OR
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> levelOrder = new ArrayList<List<Integer>>();
List<Integer> levelList = new ArrayList<Integer>();
int depth = depth(root);
for(int i=1; i<=depth; i++) {
levelOrder.add(i-1, addLevel(root, i, new ArrayList<Integer>()));
}
return levelOrder;
}
private int depth(TreeNode T) {
if(T==null) {
return 0;
}
return Math.max(depth(T.left), depth(T.right))+1;
}
private ArrayList addLevel(TreeNode T, int level, ArrayList<Integer> levelList) {
if(T==null){
return null;
}
if(level == 1) {
levelList.add(T.val);
}
addLevel(T.left, level-1, levelList);
addLevel(T.right, level-1, levelList);
return levelList;
}
No comments:
Post a Comment