Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:

Given binary tree {3,9,20,#,#,15,7},

    3
/ \
9 20
/ \
15 7

return its zigzag level order traversal as:

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

思路:与二叉树水平序解题思路几乎相同,得到水平序结果之后。再对偶数链表反转就可以。‘

代码例如以下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> list = new ArrayList<List<Integer>>();
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
dfs(0,root);
//每隔1行交换顺序
for(int i = 1; i < list.size(); i = i+2){
List<Integer> al = list.get(i);
int len = al.size();
//倒序交换
for(int j = 0; j + j < len-1; j++){
int k = al.get(j);
al.set(j, al.get(len-1-j));
al.set(len-1-j, k);
}
}
return list;
}
/**
* 中序遍历,依据深度加入list
* @param dep 树的深度
* @param root 根节点
*/
private void dfs(int dep,TreeNode root){
if(root == null){
return;
}
List<Integer> al;//依据情况得到al值
if(list.size() > dep){
al = list.get(dep);
}else{
al = new ArrayList<Integer>();
list.add(al);
}
dfs(dep+1,root.left);
al.add(root.val);
dfs(dep+1,root.right);
}
}

最新文章

  1. tst、cmp、bne、beq指令
  2. (转载)postgresql navicat 客户端连接验证失败解决方法:password authentication failed for user
  3. 开启/关闭ubuntu防火墙
  4. Android项目---listview的那些属性,常用却不常见
  5. 请教下关于CKEditor富文本编辑框设置字体颜色的问题
  6. Gson的学习与使用
  7. NEO从入门到开窗(1) - 一个智能合约的诞生
  8. Word页眉、页码的使用:利用分隔符设置指定页显示页眉,解决页码显示{PAGE \* MERGEFORMAT}问题
  9. [转帖]Shell脚本中的break continue exit return
  10. 创建 sp
  11. 2017ACM/ICPC亚洲区沈阳站-重现赛
  12. C# Math类简介运用
  13. FPGA基础知识1
  14. &lt;Android 基础(二十八)&gt; Fragment (1)
  15. JPEG图片扩展信息读取与改动
  16. 用ansible2.5在Centos7.2上部署OpenShift3.9(转)
  17. linux常见故障一:linux 文件系统变只读
  18. WordPress前台后台出现一片空白的原因以及解决办法
  19. Sql Server添加单引号
  20. MUI ajax数据请求(list)

热门文章

  1. HDU 5375 Gray code (简单dp)
  2. 强悍的 vim —— 删除空行、删除注释以及加注释解注释
  3. Android学习笔记进阶18 之画图并保存图片到本地
  4. 45. Express 框架 静态文件处理
  5. JAVA配置环境
  6. HDU——T 3746 Cyclic Nacklace
  7. Sublime10个经常使用插件
  8. Android使用蓝牙连接adb调试App
  9. 非对称算法,散列(Hash)以及证书的那些事
  10. Android手机间使用socket进行文件互传实例