Leetcode-199(Java) Binary Tree Right Side View
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]
.
传送门:https://leetcode.com/problems/binary-tree-right-side-view/
用优先队列层次遍历的方法,每次遍历到一层的最后一个节点并把它保留即可。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> list = new LinkedList<Integer>(); if(root == null) return list; //保存每一层的节点,用于取出最后一个节点 Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); currentLevel.add(root); while(!currentLevel.isEmpty()) { int size = currentLevel.size(); //lastVal用于保存每层最后一个节点值 for(int i = 0; i < size - 1; i++) { TreeNode currentNode = currentLevel.poll(); if(currentNode.left != null) currentLevel.add(currentNode.left); if(currentNode.right != null) currentLevel.add(currentNode.right); } TreeNode lastNode = currentLevel.poll(); //把最后一个节点加到队列中 list.add(lastNode.val); if(lastNode.left != null) currentLevel.add(lastNode.left); if(lastNode.right != null) currentLevel.add(lastNode.right); } return list; } }