简单编程题目连载(三)
来源:互联网 发布:批发购物软件 编辑:程序博客网 时间:2024/05/21 10:02
二叉树中如何获取二叉树的层数?
注意这里获取的层数是从1开始算的,不是从0开始的。
直接上代码:
public class Node{ public int value; public Node left; public Node right; public Node(int data){ this.value = data; }}public void getHeight(Node h,int i){ if(h == null){ return i; } return Math.max(getHeight(h.left,i+1),getHeight(h.right,i+1));}
举个例子:
public class Test{ public static void main(String[] args){ Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); Node node5 = new Node(5); Node node6 = new Node(6); Node node7 = new Node(7); Node node8 = new Node(8); Node node9 = new Node(9); Node node10 = new Node(10); Node node11 = new Node(11); Node node12 = new Node(12); Node node13 = new Node(13); Node node14 = new Node(14); Node node15 = new Node(15); Node node16 = new Node(16); node1.left = node2; node1.right = node3; node2.right = node4; node4.left = node7; node4.right = node8; node8.right = node11; node11.left = node13; node11.right = node14; node3.left = node5; node3.right = node6; node5.left = node9; node5.right = node10; node9.left = node12; node12.left = node15; node12.right = node16; int height = getHeight(node1,0); }}
上边的二叉树返回的高度为6。
如果获取二叉树每一层上最左和最右节点?
依然以上边的二叉树为例子
创建一个二维的Node类型的数组来存每层最左和最右的节点
Node[][] edgeMap = new Node[height][2];
数组的大小由二叉树的层数来定
然后利用下方的函数即可得到每层的最左和最右节点。
public void setEdgeMap(Node h,int i,Node[][] edgeMap){ if(h == null){ return; } edgeMap[i][0] = edgeMap[i][0] == null ? h : edgeMap[i][0]; edgeMap[i][1] = h; setEdgeMap(h.left,i+1,edgeMap); setEdgeMap(h.right,i+1,edgeMap);}
这个函数做了一件什么事呢?
二维数组的0位置作为左边,1位置作为右边。
i相当于到达的层数,每到一层,遇到的第一个左节点即为当前层的最左节点,因为该遍历是一直向左延伸的。右节点只要遇到新值就更新。然后递归遍历到每一层。递归基为遇到的节点为空,就返回。
0 0
- 简单编程题目连载(三)
- 简单编程题目连载(一)
- 简单编程题目连载(二)
- 简单编程题目连载(四)——找零钱
- 简单编程题目连载(五)——找零钱
- 简单编程题目连载(六)——找零钱
- 简单编程题目连载(七)——经典台阶问题
- 简单编程题目连载(八)——最短路径问题
- 简单编程题目连载(九)——最长上升子序列
- 简单编程题目连载(十)——公共最长子序列
- 简单编程题目连载(十一)——0-1背包问题
- 简单编程题目连载(十二)——最优编辑问题
- 简单编程题目连载(十三)——拓扑结构相同子树判断
- 简单编程题目连载(十四)——最长无重复字符子串
- 简单编程题目连载(十五)——找二叉树中的最大搜索二叉子树
- hdoj简单题目(三)
- 游戏编程起源连载三
- ActionScript3游戏中的图像编程(连载三)
- ROS进二阶学习笔记(9)-- 关于Overlay:重名 package 在不同catkin workspace 中,
- 词法分析与正则表达式(三)
- project_workflow_02
- ZXing 粗暴修改扫描范围及截图范围
- 修改系统默认语言
- 简单编程题目连载(三)
- 简谈用g++编译运行c++代码流程,以及动态库静态库的创建与使用
- 更新的macOS Sierra系统后怎么在隐私中找回允许任何来源
- js表单验证
- unity笔记-20170113
- MySQL入门之时间相关函数
- 欢迎使用CSDN-markdown编辑器
- python 输入与输出
- 基于CDH5.4.5(ha)的Hbase 3节点搭建