【leetcode】103. Binary Tree Zigzag Level Order Traversal【java】使用队列,简单容易理解的方法
2017-01-03 22:47
417 查看
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
return its zigzag level order traversal as:
Subscribe to see which companies asked this question
use a queue to implement BFS. Each time when I poll a node, I add this node value to level. I use a variable
zigzag to indicate whether add from left to right or right to left. If zigzag == false, it is from left to right; if zigzag == true, it is from right to left.
And from right to left just need to use ArrayList.add(0, value) method
For example:
Given binary tree
[3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
Subscribe to see which companies asked this question
use a queue to implement BFS. Each time when I poll a node, I add this node value to level. I use a variable
zigzag to indicate whether add from left to right or right to left. If zigzag == false, it is from left to right; if zigzag == true, it is from right to left.
And from right to left just need to use ArrayList.add(0, value) method
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //非递归:使用队列 public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> res = new LinkedList<List<Integer>>(); if (root == null){ return res; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); boolean isZigzag = false; while (!queue.isEmpty()){ List<Integer> subList = new LinkedList<Integer>(); int count = queue.size(); for (int i = 0; i < count; i++){ TreeNode node = queue.poll(); if (isZigzag){ subList.add(0,node.val); } else { subList.add(node.val); } if (node.left != null){ queue.add(node.left); } if (node.right != null){ queue.add(node.right); } } res.add(subList); isZigzag = !isZigzag; } return res; } }
相关文章推荐
- 【leetcode】99. Recover Binary Search Tree【java】简单又容易理解的中序遍历的方法
- Java数据结构之队列的简单定义与使用方法
- 用类名做方法的返回值类型 在学习Java的初始阶段,很多同学使用基本数据类型定义变量和引用类型定义变量以及使用类名做方法的返回值类型常常不知所以。今天我以自己的解读方式和个人的理解作一个简单的解释,和
- 对Java方法内部使用this访问成员变量的深入理解
- java中PriorityQueue优先级队列使用方法
- java_Socket简单使用方法
- java中PriorityQueue优先级队列使用方法
- java 使用axis实现WebServise简单方法
- java中队列的使用方法
- 简单工厂-工厂方法-抽象工厂对比,给出理解思路和Java参考案例源码
- JAVA中关于set()和get()方法的理解及使用
- Java本地方法理解及通过JNI的简单实现
- 波哥学java, 5.10.3 理解main()方法 String[] args的使用 向 java 中传递参数
- 使用Java实现简单的server/client回显功能的方法介绍
- java使用正则表达为数字添加千位符的简单方法
- DWR中调用Java对象的方法,不要使用简单数据类型
- JAVA减少内存使用的10个简单方法
- 简单的使用jni调用java方法
- 简单的使用jni调用java方法
- java并发-使用内置条件队列实现简单的有界缓存