# Binary Tree Level Order Traversal

86人阅读 评论(0)

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 [3,9,20,null,null,15,7],

    3
/ \
9  20
/  \
15   7


return its level order traversal as:

[
[3],
[9,20],
[15,7]
]

public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
int depth = 1;
List<List<Integer>> lst = new ArrayList<List<Integer>>();
levelOrder(lst,depth,root);
return lst;
}
public void levelOrder(List<List<Integer>> lst,int depth,TreeNode root){
if(root == null){
return;
}else{
if(lst.size() < depth){
List<Integer> lsIn = new ArrayList<Integer>();
}
List<Integer> ls = lst.get(depth - 1);
if(root.left != null){
levelOrder(lst,depth+1,root.left);
}
if(root.right != null){
levelOrder(lst,depth+1,root.right);
}

}

}
}

public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
int cnt = 0;
int f = 0;
int t = 1;
List<List<Integer>> lsts = new ArrayList<List<Integer>>();
List<Integer> lst = new ArrayList<Integer>();
List<TreeNode> nodeList = new ArrayList<TreeNode>();
if(root == null){
return 	lsts;
}
while(t != 0){
if(f == t){
t = cnt;
f = 0;
cnt = 0;
lst = new ArrayList<Integer>();
}
else{
TreeNode node = nodeList.get(0);
if(node != null){
f ++;
}
if(node.left != null){
cnt ++;
}
if(node.right != null){
cnt ++;
}
nodeList.remove(node);
}
}
return 	lsts;
}
}

public List<List<Integer>> levelOrder(TreeNode root) {
int cnt = 0;
int f = 0;
int t = 1;
List<List<Integer>> lsts = new ArrayList<List<Integer>>();
List<Integer> lst = new ArrayList<Integer>();
List<TreeNode> nodeList = new ArrayList<TreeNode>();
if(root == null){
return 	lsts;
}
while(t != 0){
if(f == t){
t = cnt;
f = 0;
cnt = 0;
lst = new ArrayList<Integer>();
}
else{
TreeNode node = nodeList.get(0);
if(node != null){
f ++;
}
if(node.left != null){
cnt ++;
}
if(node.right != null){
cnt ++;
}
nodeList.remove(0);
}
}
return 	lsts;
}

public List<List<Integer>> levelOrder(TreeNode root) {
int cnt = 0;
int f = 0;
int t = 1;
int index;
List<List<Integer>> lsts = new ArrayList<List<Integer>>();
List<Integer> lst = new ArrayList<Integer>();
List<TreeNode> nodeList = new ArrayList<TreeNode>();
if(root == null){
return 	lsts;
}
index = 0;
while(t != 0){
if(f == t){
t = cnt;
f = 0;
cnt = 0;
lst = new ArrayList<Integer>();
}
else{
TreeNode node = nodeList.get(index ++);
if(node != null){
f ++;
}
if(node.left != null){
cnt ++;
}
if(node.right != null){
cnt ++;
}
}
}
return 	lsts;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：46284次
• 积分：1080
• 等级：
• 排名：千里之外
• 原创：57篇
• 转载：44篇
• 译文：0篇
• 评论：3条
评论排行