DFS Solution

  • 1
    public List<Integer> rightSideView(TreeNode root) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            dfs(map, root, 0);
            return new ArrayList<Integer>(map.values());
        private void dfs(Map<Integer, Integer> map, TreeNode node, int depth) {
            if (node == null) return; 
            map.put(depth, node.val);
            dfs(map, node.left, depth + 1);
            dfs(map, node.right, depth + 1);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.