普通层序遍历:
//打印
public List<List<Integer>> levelOrder5(TreeNode root) {
List<List<Integer>> ret = new LinkedList<>();
levelOrder5(root, 0, ret);
return ret;
}
private void levelOrder5(TreeNode root, int level, List<List<Integer>> ret) {
if(root==null)
return ;
if(ret.size()==level){
ret.add(new LinkedList<>());
}
ret.get(level).add(root.val);
levelOrder5(root.left, level+1, ret);
levelOrder5(root.right, level+1, ret);
}
之字形层序遍历
//之字形打印
public List<List<Integer>> levelOrder4(TreeNode root) {
List<List<Integer>> ret = new LinkedList<>();
levelOrder4(root, 0, ret);
return ret;
}
private void levelOrder4(TreeNode root, int level, List<List<Integer>> ret) {
if(root==null)
return ;
if(ret.size()==level){
ret.add(new LinkedList<>());
}
if(level%2 == 0){
ret.get(level).add(root.val);
}else{
ret.get(level).add(0, root.val);
}
levelOrder4(root.left, level+1, ret);
levelOrder4(root.right, level+1, ret);
}
网友评论