[LeetCode]Binary Tree Zigzag Level Order Traversal
2015-12-04 09:25
447 查看
public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (root == null) { return result; } Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); boolean flg = true; while (!stack.isEmpty()) { List<Integer> list = new ArrayList<Integer>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); while (!stack.isEmpty()) { TreeNode node = stack.pop(); list.add(node.val); if (flg) { if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } else { if (node.right != null) { queue.offer(node.right); } if (node.left != null) { queue.offer(node.left); } } } while (!queue.isEmpty()) { stack.push(queue.poll()); } flg = !flg; result.add(list); } return result; } }
下面的方法代码复杂度低一些
public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (root == null) { return result; } boolean flg = false; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> list = new LinkedList<Integer>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (flg) { list.add(0, node.val); } else { list.add(node.val); } if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } result.add(list); flg = !flg; } return result; } }
相关文章推荐
- 轻松学习JavaScript九:JavaScript对象和数组
- JavaWeb中JavaMail创建邮件和发送邮件
- java中几个关键字 this static final
- 第十周项目3-利用二叉树遍历思想解决问题(3)
- WIFI视频传输方案
- Ubuntu14.04编译 Android5.0
- asp.net 分页思想+mvc 分页
- CNN网络提取哪层输出作为最后提取的特征为宜?
- 轻松学习JavaScript八:JavaScript函数
- 商务英语句型03
- windows平台进程CPU占用率的计算
- 学习node-inspector的调试技巧
- .net web弹出对话框
- 重新拾起linux c
- web服务器并发优化(nginx+多实例tomcat负载均衡)(另附:安装包和文档)
- 第十周项目3-利用二叉树遍历思想解决问题(2)
- Javascript技术难点之apply,call与this之间的衔接
- jquery遍历表格 每一行 值
- UEFI引导系统
- directio mysql 编绎选项