美文网首页
打印二叉树的左视图或者右视图

打印二叉树的左视图或者右视图

作者: 孙大硕 | 来源:发表于2019-04-14 14:25 被阅读0次

给定一个二叉树,打印从左边看到的,或者从右边看到的

[力扣链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/](https://leetcode-cn.com/problems/binary-tree-right-side-view/)

分析:可以参考广度优先遍历
解法1

public List<Integer> rightSideView(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
               //对每一行操作
            while(size > 0) {
                
                TreeNode current = queue.poll();
                
                if (current.left!=null) {
                    queue.offer(current.left);
                }
                if (current.right != null) {
                    queue.offer(current.right);
                }
                
                size --;
                //表示是每一行的最后一个
                if (size == 0) {
                    result.add(current.value);
                }
                
            }
        }
        return result;
    }

解法2 递归

public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
       rightSideView(root,list,0);
        return list;
    }
     public void rightSideView(TreeNode root, List<Integer> list ,int level) {
        if (root == null) {
            return;
        }
        
        if (level == list.size()) {
            list.add(root.val);
        }
        rightSideView(root.right,list,level+1);
        rightSideView(root.left,list,level + 1);
        
    }

打印左视图和右视图相似,只需在加入队列的时候先加入左结点

相关文章

  • 打印二叉树的左视图或者右视图

    给定一个二叉树,打印从左边看到的,或者从右边看到的 [力扣链接](https://leetcode-cn.com/...

  • LeetCode 第 883 题:三维形体投影面积

    1、前言 2、思路 分为俯视图、左视图、右视图。俯视图只要是不为0,直接 +1 就行;左视图直接找每行最大的;右视...

  • 室内及家具图样的表达

    这一次我们要学习家具图样的表达,比如,六视图的表达,主视图,俯视图,左视图,后视图,仰视图,右视图,以及家具装配图...

  • Swift封装-滑出式导航栏

    前言:本文将会创建以下几个主类: DWContainerViewController:这包含了左视图,中视图和右视...

  • 从上往下打印二叉树

    题目描述: 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 分析: 二叉树的遍历:前序遍历:根->左->右...

  • C4D 快捷键

    快捷键功能-F1透视图F2顶视图F3右视图F4正视图F5四视图鼠标中键透视图/四视图切换alt+鼠标左+拖拽旋转视...

  • 最简单的抽屉式原理 视图:左视图、右视图 左

    #import "ViewController.h" @interface ViewController (){ ...

  • SQL基础-3

    1、99语法内连接 等值连接 非等值连接外链接 全连接 左外链接 右外链接2、视图与索引创建视图 删除视图索引 ...

  • iOS 抽屉效果实现

    1.添加需要实现抽屉效果的三个视图,这里需要注意主视图需要放在最后添加 2.实现左滑显示左边视图,右滑出现右边视图...

  • 二叉树续

    199. 二叉树的右视图 层级遍历取每层最后一个

网友评论

      本文标题:打印二叉树的左视图或者右视图

      本文链接:https://www.haomeiwen.com/subject/qiujwqtx.html