题目
思路
- 计算每个左右子树的深度,如果深度之差大于1,那么此二叉树就不是平衡二叉树,否则就是平衡二叉树
代码
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}**/
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root ==null)
return true;
boolean flag = IsBalanced_Solution_1(root);
boolean flag1 = IsBalanced_Solution_1(root.right);
boolean flag2 = IsBalanced_Solution_1(root.left);
if(flag==true && flag1==true && flag2==true)
return true;
else
return false;
}
public boolean IsBalanced_Solution_1(TreeNode root) {
if(root ==null)
return true;
Queue<TreeNode> queue = new LinkedList<>();
int lengthleft = 0;
int lengthright =0;
if(root==null)
return true;
queue.add(root);
while(queue.size()!=0){
for(int i=0;i<queue.size();i++){
TreeNode temp = queue.poll();
if(temp.right!=null){
queue.add(temp.right);
lengthright++;
}
if(temp.left!=null){
queue.add(temp.left);
lengthleft++;
}
}
}
int len =0;
if(lengthright>lengthleft)
len = lengthright-lengthleft;
else
len = lengthleft-lengthright;
if(len<=1)
return true;
else
return false;
}
}
通过的代码
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}**/
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root ==null)
return true;
int flag1 = TreeDepth(root.right);
int flag2 = TreeDepth(root.left);
int len =0;
if(flag1>flag2)
len =flag1-flag2;
else
len =flag2-flag1;
if(len<=1)
return true;
else
return false;
}
public int TreeDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
int length = 0;
if(root==null)
return 0;
queue.add(root);
while(queue.size()!=0){
length++;
for(int i=0;i<queue.size();i++){
TreeNode temp = queue.poll();
if(temp.right!=null)
queue.add(temp.right);
if(temp.left!=null)
queue.add(temp.left);
}
}
return length;
}
}
牛客优秀代码
链接:https://www.nowcoder.com/questionTerminal/8b3b95850edb4115918ecebdf1b4d222
来源:牛客网
public class Solution {
//判断根节点左右子树的深度,高度差超过1,则不平衡
public boolean IsBalanced_Solution(TreeNode root) {
if (root==null) {
return true;
}
int left = getTreeDepth(root.left);
int right = getTreeDepth(root.right);
return Math.abs(left-right)>1?false:true;
}
//求取节点的深度
public static int getTreeDepth(TreeNode root) {
if (root==null) {
return 0;
}
int leftDepth = 1+getTreeDepth(root.left);
int rightDepth = 1+getTreeDepth(root.right);
return leftDepth>rightDepth?leftDepth:rightDepth;
}
}