原题网址:https://leetcode.com/problems/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]
.
方法:深度优先。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private void rightmost(TreeNode root, int depth, List<Integer> list) {
if (depth == list.size()) list.add(root.val);
if (root.right != null) rightmost(root.right, depth + 1, list);
if (root.left != null) rightmost(root.left, depth + 1, list);
}
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
rightmost(root, 0, list);
return list;
}
}