102. Binary Tree Level Order Traversal
Link
難易度 : Medium
依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :
- 102.二叉树的层序遍历
- 107.二叉树的层次遍历II
- 199.二叉树的右视图
- 637.二叉树的层平均值
- 429.N叉树的层序遍历
- 515.在每个树行中找最大值
- 116.填充每个节点的下一个右侧节点指针
- 117.填充每个节点的下一个右侧节点指针II
- 104.二叉树的最大深度
- 111.二叉树的最小深度
那麼就直接開始吧!!!
給予一個binary tree,要求回傳list包含由上至下,由左至右,各"層"的node val。
題目其實不難,利用queue依序將遍尋到的node加入,並且也因為queue的特性可以依次繼續向下遍尋。
class Solution
{
public List<List<Integer>> levelOrder(TreeNode root)
{
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
TreeNode current;
if(root==null)
{
return result;
}
queue.add(root);
while(!queue.isEmpty())
{
int size = queue.size();
List<Integer> tuple = new ArrayList<Integer>();
//遍尋此層數量的所有node 之後加入的不與理會
for(int i=0;i<size;i++)
{
current = queue.poll();
tuple.add(current.val);
if(current.left!=null)
{
queue.add(current.left);
}
if(current.right!=null)
{
queue.add(current.right);
}
}
if(tuple.size()>0)
{
result.add(tuple);
}
}
return result;
}
}
這一題的code可以用來當作這類型廣度優先的模板,並且接下來的9題基本上也都可以用這個模板解決,當然效率有好有壞,那就是後話了~