题目:

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 static List<Integer> rightSideView(TreeNode root){
List<Integer> arr1 = new ArrayList<Integer>();
List<Integer> arr2 = new ArrayList<Integer>();
//根节点为空返回空集合
if(root == null){
return arr1;
}
arr1.add(root.val);
arr2.add(root.val);
//获取左子树的每层最外侧结点值集合
rightSideView(root.left, arr1);
//获取右子树的每层最外侧结点值集合
rightSideView(root.right, arr2);
//如果左子树集合元素多于右子树,说明左子树高度大于右子树
if(arr1.size() > arr2.size()){
int num = arr2.size();
for(int i = num; i < arr1.size(); i++){
arr2.add(arr1.get(i));
}
}
return arr2;
} //该函数是同样的思想,每次获取左右子树的每层最外侧结点值集合
//如果左子树集合元素多于右子树,说明左子树高度大于右子树
public static void rightSideView(TreeNode root, List<Integer> arr) {
List<Integer> arr1 = new ArrayList<Integer>();
List<Integer> arr2 = new ArrayList<Integer>();
if(root == null){
return;
}
arr1.add(root.val);
arr2.add(root.val);
rightSideView(root.left,arr1);
rightSideView(root.right,arr2);
if(arr1.size() > arr2.size()){
int num = arr2.size();
for(int i = num; i < arr1.size(); i++){
arr2.add(arr1.get(i));
}
}
for(int i :arr2){
arr.add(i);
} }

最新文章

  1. Nginx配置单主机多域名
  2. String的length()和Array的length
  3. iOS - OC NSStream 文件流
  4. FIR数据广播结构-提高时钟速率
  5. char、nvarchar和varchar区别
  6. Mac下安装Redis图解教程
  7. linux产生静态库和动态库
  8. Image控件的简单使用示例1
  9. PHP提取字符串中的所有汉字
  10. 怎样获取HTML5视频的持续时间
  11. 迭代DOM集合的几种方法
  12. Angular2 ng2-smart-table
  13. Javascript学习--BOM操作
  14. python super超类方法
  15. Java中的强引用和弱引用
  16. bootstrapValidator关于js,jquery动态赋值不触发验证(不能捕获“程序赋值事件”)解决办法
  17. Leaflet中添加的不同图层样式图标
  18. jQuery delay() 方法
  19. Mass Change Queries CodeForces - 911G (线段树合并)
  20. 深入理解JavaScript函数参数

热门文章

  1. URAL 1133. Fibonacci Sequence
  2. &#39;Could not load NIB in bundle: &#39;NSBundle xxx/storeFlix.app&gt; &#39; with name &#39;UIViewController-w6Q-ra-j06&#39; and directory &#39;StoreFlixIpad.storyboardc
  3. My Notepad
  4. C语言(4)
  5. JS引用另外JS文件的顺序问题。
  6. Redis在windows下的安装使用
  7. Struts 2入门案例及登录
  8. Odoo 采购单 加盖 电子公章
  9. mysql破解root用户密码总结
  10. 服务器由于redis未授权漏洞被攻击