Open Shawngbk opened 7 years ago
用null作为每一层的分隔符,如果队首元素后面的元素是null,则证明他是这一层唯一的元素,加入list。 层次遍历法。遍历到每层最后一个节点时,把其放到结果集中。
/**
} */ public class Solution { public List rightSideView(TreeNode root) { List list = new ArrayList<>(); if(root == null) return list; Queue que = new LinkedList<>(); que.offer(root); que.offer(null); while(!que.isEmpty()) { TreeNode top = que.poll(); if(top != null) { if(que.peek() == null) { list.add(top.val); } if(top.left != null) { que.offer(top.left); } if(top.right != null) { que.offer(top.right); } } else { if(que.isEmpty()) { break; } else { que.offer(null); } } }
return list;
} }
Amazon
用null作为每一层的分隔符,如果队首元素后面的元素是null,则证明他是这一层唯一的元素,加入list。 层次遍历法。遍历到每层最后一个节点时,把其放到结果集中。
/**
} */ public class Solution { public List rightSideView(TreeNode root) {
List list = new ArrayList<>();
if(root == null)
return list;
Queue que = new LinkedList<>();
que.offer(root);
que.offer(null);
while(!que.isEmpty()) {
TreeNode top = que.poll();
if(top != null) {
if(que.peek() == null) {
list.add(top.val);
}
if(top.left != null) {
que.offer(top.left);
}
if(top.right != null) {
que.offer(top.right);
}
} else {
if(que.isEmpty()) {
break;
} else {
que.offer(null);
}
}
}
} }