Java for LeetCode 199 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].

解题思路:

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);

	}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。