标签:io ar sp for 数据 on bs ad ef
一个笨办法用两个Queue实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root==null)
return new ArrayList<List<Integer>>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
Queue<TreeNode> tmp1 = new ArrayDeque<TreeNode> ();
Queue<TreeNode> tmp2 = new ArrayDeque<TreeNode> ();
tmp1.add(root);
boolean check = true;
while (!tmp1.isEmpty() || !tmp2.isEmpty()){
List<Integer> row = new ArrayList<Integer>();
if(check)
{
while(!tmp1.isEmpty()){
TreeNode top = tmp1.remove();
row.add(top.val);
if(top.left!=null)
tmp2.add(top.left);
if(top.right!=null)
tmp2.add(top.right);
}
check = false;
}
else{
while(!tmp2.isEmpty()){
TreeNode top = tmp2.remove();
row.add(top.val);
if(top.left!=null)
tmp1.add(top.left);
if(top.right!=null)
tmp1.add(top.right);
}
check = true;
}
result.add(0,row);
}
return result;
}
}
一个聪明的办法DFS:
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root==null)
return new ArrayList<List<Integer>>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.add(new ArrayList<Integer>());
DFS(result,root,0);
return result;
}
public void DFS(List<List<Integer>> result, TreeNode root, int level){
if(root==null)
return;
if(level==result.size())
result.add(0,new ArrayList<Integer>());
result.get(result.size()-1-level).add(root.val);
DFS(result, root.left, level+1);
DFS(result, root.right, level+1);
}
}
数据结构复习--binary tree level-order traversal
标签:io ar sp for 数据 on bs ad ef
原文地址:http://www.cnblogs.com/cs-jack-cheng/p/4121311.html