标签:get init roo 没有 solution int order turn size
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [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 { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); levelHelper(res, root, 0); // 从0开始 return res; } public void levelHelper(List<List<Integer>> res, TreeNode root, int height) { if (root == null) return; //说明没有子节点,结束 if (height == res.size()) { //仅用于create new level 的arraylist,如果当前height小于size,那么说明此level的arraylist已经存在 res.add(new ArrayList<Integer>()); } res.get(height).add(root.val);//在对应的level add所有的value levelHelper(res, root.left, height+1);//下一层 levelHelper(res, root.right, height+1); } }
102. Binary Tree Level Order Traversal
标签:get init roo 没有 solution int order turn size
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10493584.html