1,问题简述
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
2,示例
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
3,题解思路
队列的使用
4,题解程序
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class RightSideViewTest {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
t1.left = t2;
t1.right = t3;
t2.right = t5;
t3.right = t4;
List<Integer> list = rightSideView(t1);
System.out.println("list = " + list);
}
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> totalList = new ArrayList<>();
List<List<Integer>> listList = new ArrayList<>();
if (root == null) {
return totalList;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> list = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
listList.add(list);
}
for (List<Integer> list : listList) {
totalList.add(list.get(list.size() - 1));
}
return totalList;
}
}
5,题解程序图片版
6,总结
队列的特点就是先进先出。队列不过也存在普通队列和优先级队列,类似超市购物排队付钱的场景,这就是队列日常中很常见的操作,一点理解,进行输出一下,这也是自己输出内容的原因,文字的记录要比口头说下更有力量