给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[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>> levels = new ArrayList<List<Integer>>();public void helper(TreeNode node, int level) {if (levels.size() == level){levels.add(new ArrayList<Integer>());}levels.get(level).add(node.val);if (node.left != null)helper(node.left, level + 1);if (node.right != null)helper(node.right, level + 1);}public List<List<Integer>> levelOrder(TreeNode root) {if (root == null) return levels;helper(root, 0);return levels;}
}