Skip to content

Latest commit

 

History

History
executable file
·
51 lines (42 loc) · 1.05 KB

199.md

File metadata and controls

executable file
·
51 lines (42 loc) · 1.05 KB

题目描述

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   \
2     3         <---
 \     \
  5     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> ans = new LinkedList<>();
        dfs(root, 0, ans);
        return ans;
    }

    public void dfs(TreeNode root, int n, List<Integer> ans) {
        if (root == null) return;
        // 只保留每一层的第一个节点
        if (n == ans.size()) {
            ans.add(root.val);
        }
        dfs(root.right, n + 1, ans);
        dfs(root.left, n + 1, ans);
    }
}