问题:给定一颗二叉树,判定其是否为平衡二叉树。
二叉树的结构为:
//Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
方法一:首先可以求出每一个节点的高度(采用递归的方法),然后再判断每一个节点是否符合平衡的条件(即| leftHeight-rightHeight | <= 1)(采用递归的方法)。此方法的时间复杂度应该是O(n^2)
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
if(Math.abs(getHeight(root.left)-getHeight(root.right)) <=1 && isBalanced(root.left) && isBalanced(root.right))
return true;
else
return false;
}
public int getHeight(TreeNode root){
if(root == null)
return 0;
return Math.max(getHeight(root.left),getHeight(root.right)) + 1;
}
}方法二:此方法只使用一次递归,在遍历树的同时也做树是否平衡的判断。此方法的时间复杂度应该是O(n)
public class Solution {
public boolean isBalance = true;
public boolean isBalanced(TreeNode root){
maxDepth(root);
return isBalance;
}
public int maxDepth(TreeNode root){
if(root == null)
return 0;
int leftH = maxDepth(root.left);
int rightH = maxDepth(root.right);
if(Math.abs(leftH - rightH) > 1)
isBalance = false;
return Math.max(leftH,rightH) + 1;
}
}
本文深入探讨了二叉树平衡性的概念及其重要性,详细介绍了两种算法来判断二叉树是否为平衡二叉树。通过递归方法求节点高度,并在遍历过程中实时验证平衡条件,实现了一次递归的高效解决方案。
887

被折叠的 条评论
为什么被折叠?



