您的位置:首页 > 其它

LeetCode 199. Binary Tree Right Side View(二叉树右侧视图)

2016-05-04 03:32 411 查看
原题网址: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: