199. 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.
Example:
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
思路:题目意思为给定一个二叉树,想象你从二叉树的右边看过去,返回你能看到的节点的值。按顺序递归每层的值传入List中。
代码如下:
public class BinaryTreeRightSideView { public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new ArrayList<>(); dfs(root, res, 0); return res; } public static void dfs(TreeNode node, List<Integer> res, int deepth) { if (node == null) return; if (deepth == res.size()){ res.add(node.val); } dfs(node.right, res, deepth + 1); dfs(node.left, res, deepth + 1); } }