LeetCode Binary Tree Right Side View

Description:

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

Solution:

每一层从右到左的BFS,然后把最右的记录下来即可。

import java.util.*;

public class Solution {
	public List<Integer> rightSideView(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
		LinkedList<Integer> layer = new LinkedList<Integer>();

		queue.add(root);
		layer.add(0);

		TreeNode node;
		int l, preLayer = -1;
		while (!queue.isEmpty()) {
			node = queue.pop();
			l = layer.pop();
			if (node == null)
				continue;

			if (l != preLayer) {
				preLayer = l;
				list.add(node.val);
			}

			if (node.right != null) {
				queue.add(node.right);
				layer.add(l + 1);
			}
			if (node.left != null) {
				queue.add(node.left);
				layer.add(l + 1);
			}
		}

		return list;
	}
}


阅读更多
文章标签: java leetcode BFS
个人分类: 算法/oj
上一篇LeetCode House Robber
下一篇LeetCode Number of Islands
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭