LeetCode 199. Binary Tree Right Side View 解题报告

199. Binary Tree Right Side View

My Submissions
Total Accepted: 34521  Total Submissions: 104860  Difficulty: Medium

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

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    求一棵二叉树的右视图。用BFS的方式遍历二叉树,取每层的最后一个节点。

    我的AC代码

public class BinaryTreeRightSideView {

	public static void main(String[] args) {
		TreeNode n1 = new TreeNode(2);
		TreeNode n2 = new TreeNode(1);
		n1.left = n2;

		System.out.println(rightSideView(n1));
	}
	public static List<Integer> rightSideView(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		if(root == null) return list;
		Queue<TreeNode> queue = new  ArrayDeque<TreeNode>();
		queue.add(root);
		queue.add(new TreeNode(Integer.MIN_VALUE));
		if(root.left != null) queue.add(root.left);
		if(root.right != null) queue.add(root.right);
		TreeNode pre = queue.poll();
		while (!queue.isEmpty()) {
			TreeNode cur = queue.poll();
			if(cur.val == Integer.MIN_VALUE) {
				list.add(pre.val);
				if(!queue.isEmpty()) queue.add(new TreeNode(Integer.MIN_VALUE));
			} else {
				if(cur.left != null) queue.add(cur.left);
				if(cur.right != null) queue.add(cur.right);
				pre = cur;
			}
		}
		return list;
        
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值