标签:
标题: | Binary Tree Right Side View |
通过率: | 27.9% |
难度: | 中等 |
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / 2 3 <--- \ 5 4 <---
You should return [1, 3, 4]
.
本题就是个按层次遍历的一种延伸,按层遍历时每次讲每一层的最后一个元素放入结果的list中即可,代码如下:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public ArrayList<Integer> rightSideView(TreeNode root) { 12 ArrayList<Integer> res=new ArrayList<Integer>(); 13 LinkedList<TreeNode> queue=new LinkedList<TreeNode>(); 14 int count=1,tmp=0; 15 if(root==null)return res; 16 queue.addLast(root); 17 while(!queue.isEmpty()){ 18 tmp=0; 19 for(int i=1;i<=count;i++){ 20 TreeNode tmptree=queue.removeFirst(); 21 if(i==count)res.add(tmptree.val); 22 if(tmptree.left!=null){ 23 queue.addLast(tmptree.left); 24 tmp++; 25 } 26 if(tmptree.right!=null){ 27 queue.addLast(tmptree.right); 28 tmp++; 29 } 30 31 } 32 count=tmp; 33 } 34 return res; 35 } 36 }
leetcode------Binary Tree Right Side View
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4395999.html