给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
答案:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
circle(root, res, 0);
return res;
}
public void circle(TreeNode root, List<List<Integer>> res, int level) {
if(root == null) {
return;
}
if(res.size() == level) {
res.add(new ArrayList<>());
}
if((level & 1) == 1) { //相当于level/2,奇数层
res.get(level).add(0, root.val); //奇数层插入到前面
} else {
res.get(level).add(root.val);
}
circle(root.left, res, level + 1);
circle(root.right, res, level + 1);
}
}