博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从右边看二叉树
阅读量:7254 次
发布时间:2019-06-29

本文共 1709 字,大约阅读时间需要 5 分钟。

hot3.png

原题

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

题目大意

  给定一个二叉树,想象自己站在树的右边,返回从下到下你能看到的节点的值。

解题思路

  二叉树的层次遍历,每层按照从左向右的顺序依次访问节点,(每一层取最右边的结点)

代码实现

树结点类

public class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x) {        val = x;    }}

 

实现类

public class Solution {    public List
rightSideView(TreeNode root) { List
result = new LinkedList<>(); if (root != null) { Deque
deque = new LinkedList<>(); // 当前层的结点数 int current = 1; // 下一层的结点数 int next = 0; TreeNode node; deque.addLast(root); while (deque.size() > 0) { // 取第一个结点 node = deque.removeFirst(); current--; // 添加非空的左结点 if (node.left != null) { next++; deque.addLast(node.left); } // 添加非空的右结点 if (node.right != null) { next++; deque.addLast(node.right); } // 如果当前层已经处理完了 if (current == 0) { // 保存此层的最右一个结点值 result.add(node.val); // 设置下一层的元素个数 current = next; next = 0; } } } return result; }}

转载于:https://my.oschina.net/u/2822116/blog/813100

你可能感兴趣的文章
ubuntu 14.04 LTS 右键菜单解压压缩包时出错
查看>>
SVN服务器搭建--Subversio与TortoiseSVN的配置安装
查看>>
2017-2018-1 20155301 《信息安全系统设计基础》第八周学习总结
查看>>
jquery ajax 提交表单(file && input)
查看>>
mysql中BIT_COUNT BIT_OR
查看>>
HDU 1317(Floyd判断连通性+spfa判断正环)
查看>>
Mysql 查询缓存
查看>>
python入门の缩进魔术
查看>>
DP专题
查看>>
html标签
查看>>
vmware 中Linux系统怎么连接外网?
查看>>
js获取元素位置和style的兼容性写法
查看>>
博客写起来一周年了~
查看>>
bootstrap学习笔记<六>(表单二之按钮)
查看>>
springcloud(十三):Eureka 2.X 停止开发,但注册中心还有更多选择:Consul 使用详解...
查看>>
JS+CSS带数字和左右按钮可控制切换的图片幻灯
查看>>
Web API Request Content多次读取
查看>>
Debian VI高亮显示及注释颜色过灰暗更改办法
查看>>
面对对象基础
查看>>
Spark内存管理
查看>>