您的位置:首页 > 其它

[Leetcode] binary tree 右视问题

2015-08-17 10:10 507 查看
[1] Populating Next Right Pointers in Each Node

[2] Populating Next Right Pointers in Each Node II

[3] Binary Tree Right Side View

一、参考我的另一篇博客

二、同一

三、使用层次遍历方式,但是要记录每一层的最后一个node

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<Integer> res = new LinkedList<Integer>();
if(root==null) return res;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
TreeNode current = null;
for(int i=0;i<size;i++){
current = queue.poll();
if(current.left!=null) queue.offer(current.left);
if(current.right!=null) queue.offer(current.right);
}
res.add(current.val);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: