给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
思想:递归
public List<List<Integer>> levelOrder(TreeNode root) { List<TreeNode> que = new LinkedList<>(); List<List<Integer>> res = new LinkedList<>(); if(root==null) return res; que.add(root); return getNextChild(res,que); } public List<List<Integer>> getNextChild(List<List<Integer>> res,List<TreeNode> que){ if(que.size()==0) return res; List<Integer> Nres = new LinkedList<>(); List<TreeNode> Nque = new LinkedList<>(); for(TreeNode node:que) { if(node!=null) { Nres.add(node.val); if(node.left!=null) Nque.add(node.left); if(node.right!=null) Nque.add(node.right); } } res.add(Nres); return getNextChild(res,Nque); }