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