[Leetcode] binary tree 右视问题
[1] Populating Next Right Pointers in Each Node
[2] Populating Next Right Pointers in Each Node II
[3] Binary Tree Right Side View
一、参考我的另一篇博客
二、同一
三、使用层次遍历方式,但是要记录每一层的最后一个node
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 import java.util.*; 11 public class Solution { 12 public List<Integer> rightSideView(TreeNode root) { 13 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 14 List<Integer> res = new LinkedList<Integer>(); 15 if(root==null) return res; 16 queue.offer(root); 17 while(!queue.isEmpty()){ 18 int size = queue.size(); 19 TreeNode current = null; 20 for(int i=0;i<size;i++){ 21 current = queue.poll(); 22 if(current.left!=null) queue.offer(current.left); 23 if(current.right!=null) queue.offer(current.right); 24 } 25 res.add(current.val); 26 } 27 return res; 28 } 29 }