算法分析:
- 深搜,根据不同layer加入不同的列表
- 对应layer的元素,加入索引为layer的列表
- 注意:从左子树开始深搜
代码:
/*** 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 {List<List<Integer>> order = new ArrayList<>();void layerTree(TreeNode root, int layer){if(root == null){return ;}// 如果当前层的列表还不存在,则创建一个新的列表if (order.size() == layer) {order.add(new ArrayList<>());}order.get(layer).add(root.val);layerTree(root.left, layer + 1);layerTree(root.right, layer + 1);}public List<List<Integer>> levelOrder(TreeNode root) {layerTree(root, 0);return order;}
}