美文网首页
二叉树的右视图

二叉树的右视图

作者: 我知他风雨兼程途径日暮不赏 | 来源:发表于2020-04-22 09:52 被阅读0次

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

1. 题目

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /     \
2       3         <---
 \        \
  5        4       <---

2. JAVA解答

首先获取树深度(M),我们只需要将循环M次,每次获取每层的最右边节点,即后序遍历即可。


时间复杂度O(N*M)空间复杂度O(M)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /***
         * 获取树深度
         */
        int deepTree(TreeNode root){
            if(root==null){
                return 0;
            }
            if(root.left==null && root.right==null){
                return 1;
            }
            if(root.left!=null && root.right!=null){
                return Math.max(deepTree(root.left),deepTree(root.right))+1;
            }else if(root.left==null){
                return deepTree(root.right)+1;
            }else{
                return deepTree(root.left)+1;
            }
        }

        /***
         * 获取树的具体层的
         */
        public int treeGetLgorithm(TreeNode root,int layer){
            if(layer==0){
                return root.val;
            }
            int res = Integer.MIN_VALUE;
            if(root.right!=null){
                res = treeGetLgorithm(root.right,layer-1);
            }
            if(res==Integer.MIN_VALUE){
                if(root.left!=null){
                    return treeGetLgorithm(root.left,layer-1);
                }

            }
            return res;
        }
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if(root==null){
                return res;
            }
            res.add(root.val);
            int layer = deepTree(root);
            for(int i=1;i<layer;i++){
                res.add(treeGetLgorithm(root,i));
            }
            return res;
        }
}

相关文章

  • 二叉树续

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

  • LeetCode 199. 二叉树的右视图

    199. 二叉树的右视图 题目来源:https://leetcode-cn.com/problems/binary...

  • 算法(三) 树的遍历

    2020.4.22:二叉树的右视图 1.思路:层次遍历,取最右边的元素 2.题解:https://leetcode...

  • 二叉树的右视图

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/binary...

  • 二叉树的右视图

    题目: 题目的理解: 二叉树按行来观察的话,那就是最后的node排序成数组。 python实现 想看最优解法移步此...

  • 二叉树的右视图

    题目描述 https://leetcode-cn.com/problems/binary-tree-right-s...

  • LeetCode-199-二叉树的右视图

    二叉树的右视图 题目描述:给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从...

  • 199. 二叉树的右视图

    二叉树的右视图给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例: ...

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

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

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

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

网友评论

      本文标题:二叉树的右视图

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