剑指Offer 39题 二叉树的深度 && 判断平衡二叉树 Java版
2016-10-04 02:44
471 查看
package test; public class TreeDepth { public class BinaryTreeNode{ int m_nValue; BinaryTreeNode m_pLeft; BinaryTreeNode m_pRight; } public int treeDepth(BinaryTreeNode root){ if(root == null){ return 0; } int Left = treeDepth(root.m_pLeft); int Right = treeDepth(root.m_pRight); return (Left>Right)? (Left+1) :(Right+1); } public boolean IsBalance(BinaryTreeNode root){ if(root == null){ return true; } int left = treeDepth(root.m_pLeft); int right = treeDepth(root.m_pRight); int diff = left - right; if(diff>1 || diff<-1){ return false; } return IsBalance(root.m_pLeft)&& IsBalance(root.m_pRight); } public BinaryTreeNode createTree(){ BinaryTreeNode root = new BinaryTreeNode(); root.m_nValue = 1; BinaryTreeNode n2 = new BinaryTreeNode(); n2.m_nValue = 2; BinaryTreeNode n3 = new BinaryTreeNode(); n3.m_nValue = 3; BinaryTreeNode n4 = new BinaryTreeNode(); n4.m_nValue = 4; BinaryTreeNode n5 = new BinaryTreeNode(); n5.m_nValue = 5; BinaryTreeNode n6 = new BinaryTreeNode(); n6.m_nValue = 6; BinaryTreeNode n7 = new BinaryTreeNode(); n7.m_nValue = 7; root.m_pLeft = n2; root.m_pRight = n3; n2.m_pLeft = n4; n2.m_pRight = n5; n5.m_pLeft = n7; n3.m_pRight= n6; return root; } public boolean IsBalanced(BinaryTreeNode root, int pDepth){ if(root == null){ pDepth = 0; return true; } int left=0 ,right=0; if(IsBalanced(root.m_pLeft, left)&&IsBalanced(root.m_pRight, right)){ int diff = left - right; if(diff <=1 && diff >=-1){ pDepth = 1+(left > right? left: right); System.out.println("pDepth :"+pDepth+"+++++++++==root:"+root.m_nValue); return true; } } return false; } public boolean IsBalanced(BinaryTreeNode root){ int pDepht = 0; return IsBalanced(root,pDepht); } public static void main(String[] args){ TreeDepth treeDepth = new TreeDepth(); BinaryTreeNode root = treeDepth.createTree(); // System.out.println(treeDepth.treeDepth(root)); // // System.out.println(treeDepth.IsBalance(root)); System.out.println(treeDepth.IsBalanced(root)); } }
相关文章推荐
- 剑指Offer_面试题39_二叉树的深度 & 判断平衡二叉树
- 剑指offer 面试题39 求二叉树深度|判断是否为平衡二叉树
- 【面试题】剑指Offer-39-求二叉树的深度和判断一颗树是否为平衡二叉树
- 剑指offer 39-二叉树的深度 判断二叉树是否为平衡二叉树
- 剑指Offer面试题39二叉树的深度(以及判断平衡二叉树),面试题40数组中只出现一次的数字
- 剑指offer面试题39:二叉树深度以及判断平衡二叉树
- 剑指Offer面试题39(Java版):二叉树的深度
- 剑指offer解题报告(Java版)——二叉树的深度 判断二叉树是否平衡 38
- [剑指offer]二叉树深度vs判断平衡二叉树
- 【剑指offer-Java版】39二叉树的深度
- 剑指offer 39. 二叉树的深度和判断是否为平衡二叉树
- 剑指Offer面试题39(Java版):二叉树的深度
- 剑指offer 39.判断二叉树是否为平衡二叉树
- 剑指offer 39---求二叉树的深度 && 输入一颗二叉树的根节点,判断该树是不是平衡二叉树
- 剑指offer:java判断二叉树是否对称
- 剑指offer 39题 【知识迁移能力】二叉树的深度
- 剑指offer面试题之判断一颗二叉树是不是平衡二叉树
- 剑指 offer代码解析——面试题39判断平衡二叉树
- java实现 二叉树的深度&判断二叉树是否是平衡二叉树
- 剑指 offer代码解析——面试题39判断平衡二叉树(高效方法)