首页 > 代码库 > Binary Tree Zigzag Level Order Traversal
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
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:
很简单的一个,比Binary Tree Level Order Traversal多了一个方向标志(Zigzag的方向性),
/** * Definition for binary tree * 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>> list = new LinkedList<List<Integer>>();//返回结果 Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列,使用BFS遍历 int level = 0;//记录某一层进队的元素数 int count = 0;//计数 if(root == null){ return list; } queue.offer(root); level++; TreeNode p = null; boolean flag = true;//标志Zigzap的方向 while(queue.size() > 0){ int nextLevel = 0;//下一层进队的元素数 List<Integer> tmp = new ArrayList<Integer>();//中间存储每一行的结果 while(count < level){ p = queue.poll();//出队 if(p.left != null){ queue.offer(p.left); nextLevel++; } if(p.right != null){ queue.offer(p.right); nextLevel++; } if(flag){ tmp.add(p.val); }else{ tmp.add(0,p.val); } count ++; } list.add(tmp); count = 0; level = nextLevel; flag = !flag; } return list; } }Runtime: 227 ms
Binary Tree Zigzag Level Order Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。