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
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]Solution: BFS
进行一次广度优先搜索,维护一个队列,只是对于每个结点它的邻接点只有可能是左孩子和右孩子。
算法的复杂度是就结点的数量O(n),空间复杂度是一层的结点数,也是O(n)。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList> levelOrder(TreeNode root) { ArrayList > result = new ArrayList >(); if(root == null) return result; //use queue to store nodes LinkedList queue = new LinkedList (); queue.add(root); int curLevCount = 1; //nodes number in current level int nextLevCount = 0; //nodes number in next level ArrayList levelRes = new ArrayList (); while(!queue.isEmpty()) { TreeNode cur = queue.poll(); curLevCount--; levelRes.add(cur.val); if(cur.left != null) { //store current's left subnode into queue queue.add(cur.left); nextLevCount++; } if(cur.right != null) { //store current's right subnode into queue queue.add(cur.right); nextLevCount++; } if(curLevCount == 0) { curLevCount = nextLevCount; nextLevCount = 0; result.add(levelRes); levelRes = new ArrayList (); } } return result; } }
No comments:
Post a Comment