1、问题描述
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]
.
2、边界条件:root==null
3、思路:从右边看,是看到了每一行的最右边一个,也就是每一行从左往右遍历的最后一个。或者从右往左遍历的第一个。
可以按照上面两种实现。
4、代码实现
方法一:从左边往右遍历:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int curLevelNum = 1; while (!queue.isEmpty()) { TreeNode top = new TreeNode(0); int nextLevelNum = 0; while (curLevelNum-- > 0) { top = queue.poll(); if (top.left != null) { queue.add(top.left); nextLevelNum++; } if (top.right != null) { queue.add(top.right); nextLevelNum++; } } result.add(top.val); curLevelNum = nextLevelNum; } return result; } }
方法二:从右往左遍历
class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int curLevelNum = 1; while (!queue.isEmpty()) { result.add(queue.peek().val); int nextLevelNum = 0; while (curLevelNum-- > 0) { TreeNode top = queue.poll(); if (top.right != null) { queue.add(top.right); nextLevelNum++; } if (top.left != null) { queue.add(top.left); nextLevelNum++; } } curLevelNum = nextLevelNum; } return result; } }