《剑指offer》-判断二叉树是否是平衡二叉树
2018-01-31 09:34
459 查看
/* * 输入一棵二叉树,判断该二叉树是否是平衡二叉树。 * 平衡二叉树的定义:是一个空树或者是一种二叉排序树,其中每一个节点的左子树和右子树的高度差至多等于 1 * 平衡二叉树一定是二叉排序树,但是二叉排序树不一定是平衡二叉树 */ public class IsBalanced_Solution { //法一:求某个节点的深度:前序遍历,从上往下,造成了底层节点的重复遍历 public boolean isBalanced_Solution(TreeNode root) { if(root == null) return true; //求其左右节点的深度 int leftDepth = TreeDepth(root.left); int rightDepth = TreeDepth(root.right); int depth_diff = leftDepth - rightDepth; if(depth_diff < -1 || depth_diff > 1) return false; return isBalanced_Solution(root.left) && isBalanced_Solution(root.right); } //法二:求某个节点的深度:后序遍历,从下往上,避免了底层节点的重复遍历 boolean isBalanced = true; public int TreeDepth(TreeNode root) { if(root == null) { return 0; } int nLeft = TreeDepth(root.left); int nRight = TreeDepth(root.right); if(Math.abs(nLeft - nRight) > 1) { isBalanced = false; } return nLeft > nRight ? (nLeft + 1) : (nRight + 1); } public boolean isBalanced_Solution2(TreeNode root) { if(root == null) return true; TreeDepth(root); return isBalanced; } public static void main(String[] args) { TreeNode root1 = new TreeNode(5); root1.left = new TreeNode(4); root1.right = new TreeNode(6); root1.left.left = new TreeNode(3); root1.left.right = new TreeNode(2); root1.left.left.left = new TreeNode(2); root1.left.left.right = new TreeNode(1); root1.left.left.left.left = new TreeNode(1); System.out.println(new IsBalanced_Solution().isBalanced_Solution2(root1)); } }
相关文章推荐
- 剑指offer(41):判断二叉树是否为平衡二叉树(AVL树)
- 【剑指offer系列之二叉树】判断是否为平衡二叉树
- 计算二叉树的深度+判断二叉树是否是平衡二叉树
- 剑指offer——二叉树的深度与平衡二叉树的判断
- 《牛客网剑指offer39题》输入一棵二叉树,判断该二叉树是否是平衡二叉树
- 判断一棵二叉树是否为搜索二叉树、完全二叉树、平衡二叉树(java)
- 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
- 判断二叉树是否为平衡二叉树
- 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
- 判断二叉树是否平衡二叉树
- 判断二叉树是否为平衡二叉树
- 判断一棵二叉树是否是平衡二叉树/求一颗二叉树的镜像
- 编程实现判断一棵二叉树是否是平衡二叉树
- 剑指offer系列之38:判断是否是平衡二叉树
- 求二叉树深度、判断是否是平衡二叉树
- 【二叉树】判断二叉树是否为平衡二叉树
- 判断一棵二叉树是否为平衡二叉树(待续!!!!)
- 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
- 【算法】判断一棵二叉树是否是平衡二叉树
- 判断一棵二叉树是否是平衡二叉树并求一颗二叉树的镜像——题集十