/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); helper(res, root, 0); return res; } private void helper(List<List<Integer>> res, TreeNode root, int depth) { if (root == null) return; if (res.size() == depth) res.add(new LinkedList<>()); res.get(depth).add(root.val); helper(res, root.left, depth + 1); helper(res, root.right, depth + 1); } }
class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> list = new ArrayList<>(); if(root == null) return list; helper(root,list,0); return list; } private void helper(TreeNode root,List<List<Integer>> list,int length){ if(root == null) return ; if(length == list.size()) list.add(new LinkedList<>()); if(length%2==0) list.get(length).add(root.val); else list.get(length).add(0,root.val); helper(root.left,list,length+1); helper(root.right,list,length+1); } }
--------------------------continue--------------------------