199. Binary Tree Right Side View
Link
難易度 : Medium
依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :
- 102.二叉树的层序遍历
- 107.二叉树的层次遍历II
- 199.二叉树的右视图
- 637.二叉树的层平均值
- 429.N叉树的层序遍历
- 515.在每个树行中找最大值
- 116.填充每个节点的下一个右侧节点指针
- 117.填充每个节点的下一个右侧节点指针II
- 104.二叉树的最大深度
- 111.二叉树的最小深度
那麼就直接開始吧!!!
題目要求回傳由上到下各層的"最右邊"的node val,那麼一樣使用這類題目的模板做法,只要在遍尋每層的時候額外判斷是否為"最後一個node"即可。
class Solution
{
public List<Integer> rightSideView(TreeNode root)
{
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<Integer> result = new ArrayList<Integer>();
TreeNode current;
if(root==null)
{
return result;
}
queue.add(root);
while(!queue.isEmpty())
{
int size = queue.size();
//遍尋此層數量的所有node 之後加入的不與理會
for(int i=0;i<size;i++)
{
current = queue.poll();
if(current.left!=null)
{
queue.add(current.left);
}
if(current.right!=null)
{
queue.add(current.right);
}
//當是此層最後一個node時
if(i==size-1)
{
result.add(current.val);
}
}
}
return result;
}
}