/**
* 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) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> list = new LinkedList<>();
dfs(root, 0, list);
return list;
}
public void dfs(TreeNode root, int depth, List<List<Integer>> res) {
if (root == null) {
return;
}
if (res.size() == depth)
res.add(new LinkedList<>());
if (depth % 2 == 0) {
res.get(depth).add(root.val);
} else {
res.get(depth).add(0, root.val);
}
dfs(root.left, depth + 1, res);
dfs(root.right, depth + 1, res);
depth++;
}
}
LeetCode-103:二叉树的锯齿形层序遍历(Java语言实现)
最新推荐文章于 2024-08-17 15:37:21 发布