java 判断一个二叉树是不是平衡二叉树
来源:互联网 发布:淘宝网披肩女装 编辑:程序博客网 时间:2024/05/22 01:53
题目:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
算法如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; if(root.left==null&&root.right==null) return true; if(root.left==null&&root.right!=null){ root = root.right; if(root.left==null&&root.right==null) return true; else return false; } if(root.right==null&&root.left!=null){ root = root.left; if(root.left==null&&root.right==null) return true; else return false; } if(root.right!=null&&root.left!=null){ boolean flag1 = isBalanced(root.right); boolean flag2 = isBalanced(root.left); if(!(flag1&&flag2)) return false; else{ int x = Math.abs(maxDepth(root.left)-maxDepth(root.right)); if(x>1){ return false; }else{ return true; } } } return true; } public int maxDepth(TreeNode root){ if(root==null){ return 0; } if(root.left==null&&root.right==null){ return 1; } if(root.left==null){ return maxDepth(root.right)+1; } if(root.right==null){ return maxDepth(root.left)+1; } if(root.left!=null&&root.right!=null){ return max(maxDepth(root.left),maxDepth(root.right))+1; } return 0; } public int max(int a,int b){ return a>b?a:b; }}
1 0
- java 判断一个二叉树是不是平衡二叉树
- 判断一个树是不是二叉平衡树
- 判断一个树是不是平衡二叉树
- 判断一个树是不是平衡二叉树
- 判断一个树是不是平衡二叉树
- 判断二叉树是不是平衡
- 判断二叉树是不是平衡
- 判断二叉树是不是平衡[
- 判断二叉树是不是平衡
- 判断二叉树是不是平衡
- 判断是不是平衡二叉树
- 判断二叉树是不是平衡
- 判断二叉树是不是平衡
- 判断二叉树是不是平衡二叉树
- 判断二叉树是不是平衡二叉树
- 判断二叉树是不是平衡二叉树
- 判断二叉树是不是平衡二叉树
- 判断二叉树是不是平衡二叉树
- iOS开发系列--单个音乐文件的播放
- 基于内容的推荐算法(推荐系统)(一)
- Jmeter入门篇
- Mysql命令大全
- 多线程简介
- java 判断一个二叉树是不是平衡二叉树
- android中给TextView设置不同的颜色
- uva 102 Ecological Bin Packing
- 使用pagerIndicator+fragment+viewPager构建常用界面框架
- leetcode——113——Path Sum II
- 【在Struts2中加入ajax异步发送请求给服务器】
- KEIL MDK 查看代码量、RAM使用情况--RO-data、RW-data、ZI-data的解释
- 错排问题
- elasticsearch报错:None of the configured nodes are available: []