For example:
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if(root==null) {
return ret;
}
ArrayList<TreeNode> fronties = new ArrayList<TreeNode>();
fronties.add(root);
while(fronties.size()!=0) {
ArrayList<Integer> level = new ArrayList<Integer>();
ArrayList<TreeNode> temp = new ArrayList<TreeNode>();
for(TreeNode frontie : fronties) {
level.add(frontie.val);
if(frontie.left!=null) {
temp.add(frontie.left);
}
if(frontie.right!=null) {
temp.add(frontie.right);
}
}
ret.add(level);
fronties = temp;
}
return ret;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null) {
return ret;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
int count = queue.size();
List<Integer> row = new ArrayList<Integer>();
while (count > 0) {
TreeNode node = queue.pop();
row.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
count--;
}
ret.add(row);
}
return ret;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null) {
return ret;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
int count = queue.size();
List<Integer> row = new ArrayList<Integer>();
while (count > 0) {
TreeNode node = queue.pop();
row.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
count--;
}
ret.add(row);
}
return ret;
}
}
没有评论:
发表评论