算法 分治法 二叉树深度
来源:互联网 发布:竞价软件有用吗 编辑:程序博客网 时间:2024/06/08 09:40
public class Test2 { static TreeNode<Integer> t1; static int leftDepth = 1; static int rightDepth = 1; public static void main(final String[] args) throws Exception { initData(); int depth = caculateDepth(t1); System.out.println(depth+""); } private static void initData() { //1.父 t1 = new TreeNode<>(154); //2.父 左 t1.addLeft(254); //父 左 左, 父 左 右 t1.leftChild.addLeft(97); t1.leftChild.addRight(101); //父 左 右 左 t1.leftChild.rightChild.addLeft(66); //父 左 右 左 左, 父 左 右 左 右 t1.leftChild.rightChild.leftChild.addLeft(33); t1.leftChild.rightChild.leftChild.addRight(100); //3.父 右 t1.addRight(354); //父 右 左 t1.rightChild.addLeft(88); } private static int caculateDepth(TreeNode t) { int depth = 0; if (t != null) { int leftDepth = caculateDepth(t.leftChild); int rightDepth = caculateDepth(t.rightChild); //从第一个解析,左边最大长度和右边最大长度,肯定取更长的+1 depth = leftDepth >= rightDepth ? leftDepth + 1 : rightDepth + 1; } return depth; }}class TreeNode<T> { T value; TreeNode<T> leftChild; TreeNode<T> rightChild; TreeNode(T value) { this.value = value; } TreeNode() { } public void addLeft(T value){ TreeNode<T> leftChild = new TreeNode<T>(value); this.leftChild = leftChild; } public void addRight(T value){ TreeNode<T> rightChild = new TreeNode<T>(value); this.rightChild = rightChild; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(!(obj instanceof TreeNode)){ return false; } return this.value.equals(((TreeNode<?>)obj).value); } @Override public int hashCode() { // TODO Auto-generated method stub return this.value.hashCode(); } @Override public String toString(){ return this.value==null?"":this.value.toString(); }}
时间复杂度:因为每个节点都只遍历了一次,所以是O(N)
阅读全文
0 0
- 算法 分治法 二叉树深度
- 分治法求解二叉树深度
- LintCode 第97题 二叉树的最大深度 【分治算法】
- 二叉树深度算法
- 二叉树深度的算法
- 二叉树深度的算法
- 二叉树最优深度算法
- 求二叉树深度的算法
- 二叉树的深度排序算法
- java 求二叉树最大深度算法
- 算法 - 求二叉树的最大深度
- 算法-求二叉树最小深度
- 算法题目-二叉树的深度
- 分治-二叉树重建
- 算法之树的分治法
- 算法(07):分治法
- 常用算法 --- 分治法
- 基础算法--分治法
- 详细解释线程与进程
- 一切都结束了
- isinstance 和 type查看数据类型
- hdu 4429 Split the Rectangle(lca+二叉树)
- 分层架构,前后端分离有啥坏处?
- 算法 分治法 二叉树深度
- 基本字符串压缩Java实现
- iOS App Development (Maximum number of certificates generated)开发证书数量到上限了怎么办
- CentOS7上Glusterfs的安装及使用(gluster/heketi)
- php根据经纬度算出公里数
- 如何把shellcode转换成exe文件分析
- 使用spring事件驱动机制,实现权限信息的自动收集存库
- 业务流程监控的几点建议
- Ctrlbox Project v2.3项目管理用户手册(四)——操作详解4.8