[leetcode-二叉树层次遍历并统计每层节点数]--103. Binary Tree Zigzag Level Order Traversal
2017-02-09 14:10
489 查看
Question 103. Binary Tree Zigzag Level Order Traversal
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,null,null,15,7],
return its zigzag level order traversal as:
二叉树层次遍历 并统计每层节点数。 此外奇数层从左到右输出,偶数层从右到左输出。 和前面的102,107题类似。
给出实现源码:
测试用例和前面一样,现在只给出测试用例输出:
满足要求。
本文完整代码的github地址:
https://github.com/leetcode-hust/leetcode/blob/master/louyuting/src/leetcode/Question103.java
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,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
二叉树层次遍历 并统计每层节点数。 此外奇数层从左到右输出,偶数层从右到左输出。 和前面的102,107题类似。
给出实现源码:
/** * 二叉树的层次遍历 * 使用队列实现 * @param root * @return */ public static List<List<Integer>> levelOrder(TreeNode root) { Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列里面存放结点 List<List<Integer>> result = new ArrayList<List<Integer>>(); int flag=1; //如果为空树就直接返回 if(root == null){ return result; } queue.offer(root);//根节点先入队 //只要队列非空就一直循环; while (!queue.isEmpty()){ int levelNum = queue.size();//获取当前层的节点数. flag++; //从右到左遍历时才使用 Stack<Integer> stack = new Stack<>(); List<Integer> subList = new ArrayList<>(); //遍历当前层结点 for(int i=0; i<levelNum; i++){ //队首出队并将value加入子list TreeNode node = queue.poll(); //偶数行就用栈存储 if(flag %2 == 1) { stack.push(node.val); }else{ subList.add(node.val); } //将非空左右子树加入queue if(node.left != null){//如果队首的左结点不为空就把左结点入队 queue.offer(node.left); } if(node.right != null){//如果队首的右结点不为空就把右结点入队 queue.offer(node.right); } } //偶数行就从栈中取数据. if(flag %2 == 1) { while (!stack.isEmpty()){ subList.add(stack.pop()); } result.add(subList); }else { result.add(subList);//添加一层 } } return result; }
测试用例和前面一样,现在只给出测试用例输出:
3, 20, 9, 15, 7,
满足要求。
本文完整代码的github地址:
https://github.com/leetcode-hust/leetcode/blob/master/louyuting/src/leetcode/Question103.java
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- C 语言二叉树几种遍历方法详解及实例
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- PHP实现的线索二叉树及二叉树遍历方法详解
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++将二叉树转为双向链表及判断两个链表是否相交
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- C语言 二叉树的链式存储实例
- C语言 数据结构之中序二叉树实例详解
- C++实现查找二叉树中和为某一值的所有路径的示例
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结