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,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
ref http://www.cnblogs.com/springfor/p/3891391.html
知道用queue但是如何控制cur level和next level,ref给出了计数var, 标准的bfs做法
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(root==null) return res; ArrayList<Integer> cl = new ArrayList<Integer>(); LinkedList<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); int curNum=1, nextNum=0; while(!q.isEmpty()){ TreeNode n = q.poll(); curNum--; cl.add(n.val); if(n.left!=null){ q.add(n.left); nextNum++; } if(n.right!=null){ q.add(n.right); nextNum++; } if(curNum==0){ res.add(cl); cl = new ArrayList<Integer>(); curNum =nextNum; nextNum = 0; } } return res; }
Binary Tree Level Order Traversal II
res.add(0,cl);
时间: 2024-10-12 08:31:55