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
复制代码

 

posted @   沧浪少年  阅读(195)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示