一种特殊的树的遍历方式
2020-06-15 本文已影响0人
抬头挺胸才算活着
普通层序遍历:
//打印
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);
}