zoukankan      html  css  js  c++  java
  • leetcode_199 Binary Tree Right Side View

    题目:

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

    给出任意一颗二叉树,返回它的每层最右边的结点值集合。

    思路:

    考虑递归解决该问题。

    首先判断根节点是否为空,为空的话直接返回空集合。

    递归的获取左右子树的每层的最外侧结点的值集合,如果左边的值集合元素个数多于右边集合的,说明左子树的高度大于右子树的,需要把多的那部分元素加入到右子树的集合中。

    代码:

     1     public static List<Integer> rightSideView(TreeNode root){
     2         List<Integer> arr1 = new ArrayList<Integer>();
     3         List<Integer> arr2 = new ArrayList<Integer>();
     4         //根节点为空返回空集合
     5         if(root == null){
     6             return arr1;
     7         }
     8         arr1.add(root.val);
     9         arr2.add(root.val);
    10         //获取左子树的每层最外侧结点值集合
    11         rightSideView(root.left, arr1);
    12         //获取右子树的每层最外侧结点值集合
    13         rightSideView(root.right, arr2);
    14         //如果左子树集合元素多于右子树,说明左子树高度大于右子树
    15         if(arr1.size() > arr2.size()){
    16             int num = arr2.size();
    17             for(int i = num; i < arr1.size(); i++){
    18                 arr2.add(arr1.get(i));
    19             }
    20         }
    21         return arr2;
    22     }
    23     
    24     //该函数是同样的思想,每次获取左右子树的每层最外侧结点值集合
    25     //如果左子树集合元素多于右子树,说明左子树高度大于右子树
    26     public static void rightSideView(TreeNode root, List<Integer> arr) {
    27         List<Integer> arr1 = new ArrayList<Integer>();
    28         List<Integer> arr2 = new ArrayList<Integer>();
    29         if(root == null){
    30             return;
    31         }
    32         arr1.add(root.val);
    33         arr2.add(root.val);
    34         rightSideView(root.left,arr1);
    35         rightSideView(root.right,arr2);
    36         if(arr1.size() > arr2.size()){
    37             int num = arr2.size();
    38             for(int i = num; i < arr1.size(); i++){
    39                 arr2.add(arr1.get(i));
    40             }
    41         }
    42         for(int i :arr2){
    43             arr.add(i);
    44         }
    45         
    46     }
    View Code
  • 相关阅读:
    元素的隐藏和显示
    dateformat-参数表
    HTTP缓存控制小结
    Shell 快捷键
    PHP中的cURL库
    选择排序法
    双系统重装windows后如何恢复ubuntu启动项
    dell 3420 独立显卡黄色感叹号不能用问题
    YUY数据转换为RGB数据,并进行灰度化处理显示
    ubuntu 15.04安装显卡驱动,出现登录界面闪烁得解决方案(dell 3420 )
  • 原文地址:https://www.cnblogs.com/bywallance/p/5570199.html
Copyright © 2011-2022 走看看