题目地址:
题目描述:给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。解答:
二叉树的层序遍历,只不过对于偶数层来说,把该层的遍历结果转置一下就行了。java ac代码:/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public List
> zigzagLevelOrder(TreeNode root) { List
> ans = new ArrayList(100); ArrayDeque deque = new ArrayDeque(1000); if(root == null)return ans; deque.offer(root); int num = 1; while(!deque.isEmpty()) { int n = deque.size(); List temp = new ArrayList(n); for(int i = 0;i < n;i++) { TreeNode node = deque.poll(); temp.add(node.val); if(node.left != null)deque.offer(node.left); if(node.right != null)deque.offer(node.right); } if((num&1) != 1) Collections.reverse(temp); ans.add(temp); num++; } return ans; }}