计算二叉树的深度,判断二叉树是否是平衡二叉树
2015-07-07 20:49
459 查看
package java_study.JianZhiOffer; import org.junit.Test; /** * Created by ethan on 2015/7/7. * 剑指offer No39计算二叉树的深度,判断二叉树是否是平衡二叉树 */ public class No39二叉树的深度 { public int getDepth(TreeNode root){ if (root == null) return 0; int left = getDepth(root.getLchild()); int right = getDepth(root.getRchild()); return (left>right?left:right)+1; } // 判断平衡二叉树的方法1: 先序的方法,这样重复遍历了 public boolean isBalanceBinaryTree(TreeNode root){ if (root==null) return true; int left = getDepth(root.getLchild()); int right = getDepth(root.getRchild()); int gap = left - right; if (Math.abs(gap)<=1){ return isBalanceBinaryTree(root.getLchild()) && isBalanceBinaryTree(root.getRchild()); }else return false; } // 判断平衡二叉树的方法2: 后序的方法,这样就不需要重复遍历了 // 但是这样就要在根节点和子节点传递深度,如果用c/c++的指针实现比较简单,用java实现实在是ugly public class Depth{ int depth; } public boolean isBanlanceBinaryTreePost(TreeNode root){ return isBanlanceBinaryTreePostImp(root, new Depth()); } public boolean isBanlanceBinaryTreePostImp(TreeNode root, Depth d){ if (root==null) { d.depth = 0; return true; } Depth d_left = new Depth(); Depth d_right = new Depth(); if (isBanlanceBinaryTreePostImp(root.getLchild(), d_left) && isBanlanceBinaryTreePostImp(root.getRchild(), d_right)){ int gap = d_left.depth - d_right.depth; if (Math.abs(gap)<=1){ d.depth = ((d_left.depth>d_right.depth)?d_left.depth:d_right.depth)+1; return true; } } return false; } @Test public void test(){ TreeNode root = TreeUtil.buildTree("478321", "872341"); TreeUtil.postOrder(root); System.out.println(); System.out.println(getDepth(root)); System.out.println(isBalanceBinaryTree(root)); System.out.println(isBanlanceBinaryTreePost(root)); } }
相关文章推荐
- 1328
- sql中常用到的GUID
- javascript内置顶层函数
- javascript数租
- eclipse下给jar增加源代码
- 字串的匹配函数Index(S,T,pos)
- 草津中文离线地图App上线
- 支持向量机(SVM)算法的matlab的实现
- IBM SVC storage
- js中的各种难题(1)
- IOS判断用户的网络类型(2/3/4G、wifi)
- COJ 1010 WZJ的数据结构(十) 线段树区间操作
- c# 抓取Web网页数据分析
- ASP.NET 5运行时升级到Beta5
- document对象
- javascript对文档对象的内容、属性、样式的操作
- UVALive 6426
- [数据结构]线性结构——栈
- JSP整理总结--9大内置对象、4个作用域
- 浅析linux中鼠标数据读取