【LeetCode】 199. Binary Tree Right Side View

来源:互联网 发布:二维数组动态分配内存 编辑:程序博客网 时间:2024/05/17 01:14

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 {    public List<Integer> rightSideView(TreeNode root) {        List<Integer> res = new ArrayList<Integer>();        helper(res, root, 0);        return res;    }        private void helper(List<Integer> res, TreeNode node, int height) {        if (node == null) {            return;        }        if (res.size() == height) {            res.add(node.val);        }        helper(res, node.right, height + 1);        helper(res, node.left, height + 1);    }}


0 0
原创粉丝点击