码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 199 Binary Tree Right Side View

时间:2015-06-07 18:38:54      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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].

解题思路:

DFS,带个height即可,JAVA实现如下:

	public List<Integer> rightSideView(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		if (root == null)
			return list;
		list.add(root.val);
		if (root.right != null)
			dfs(list, root.right, 1);
		if (root.left != null)
			dfs(list, root.left, 1);
		return list;
	}

	static void dfs(List<Integer> list, TreeNode root, int height) {
		if (height == list.size())
			list.add(root.val);
		if (root.right != null)
			dfs(list, root.right, height+1);
		if (root.left != null)
			dfs(list, root.left, height+1);

	}

 

Java for LeetCode 199 Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4558727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!