从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<List<Integer>> res = new ArrayList(); public List<List<Integer>> levelOrder(TreeNode root){ recur(root,0); return res; } public void recur(TreeNode root,int k){ if(root != null){ if(res.size() <= k) res.add(new ArrayList()); res.get(k).add(root.val); recur(root.left,k+1); recur(root.right,k+1); } } }