标签:abs while 题意 math size class list roo private
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true; //空树,是AVL树
int left = TreeDepth(root.left); //左孩子深度
int right = TreeDepth(root.right); //右孩子深度
if(Math.abs(left-right) <= 1){ //左右子树深度差《=1
//判断以左右孩子为根节点的树是否为AVL树
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
return false;
}
private int TreeDepth(TreeNode root){
if(root == null) return 0;
int left = TreeDeath(root.left);
int right = TreeDeath(root.right);
return Math.max(left,right)+1;
}
}
从上向下遍历会重复遍历下层节点,增加不必要的开销。
我们可以从下向上遍历,如果子树是平衡二叉树,则返回子树深度;如果不是平衡树,直接返回false
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true;
return TreeDepth(root) != -1;
}
private int TreeDepth(TreeNode root){
if(root == null) return 0;
int left = TreeDepth(root.left);
if(left == -1) return -1;
int right = TreeDepth(root.right);
if(right == -1) return -1;
return Math.abs(left-right)>1 ? -1 : 1+Math.max(left,right);
}
}
使用非递归计算每个节点左右子树的深度,根据深度差判断是否是平衡二叉树。
import java.util.*;
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true;
int left = depth(root.left);
int right = depth(root.right);
if(Math.abs(left-right) <= 1){
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
return false;
}
private int depth(TreeNode root){
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int depth = 0;
int size = 0;
while(!queue.isEmpty()){
depth ++;
size = queue.size();
while(size > 0){
root = queue.poll();
if(root.left != null) queue.add(root.left);
if(root.right != null) queue.add(root.right);
size --;
}
}
return depth;
}
}
标签:abs while 题意 math size class list roo private
原文地址:https://www.cnblogs.com/le-le/p/12828975.html