本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
解法一:递归法,求每一个节点的左右子树高度,差值大于1就返回-1,-1作为标志判断最后的结果
class Solution {
public boolean isBalanced(TreeNode root) {
int result = dG(root);
return result != -1 ? true:false;
}
public int dG(TreeNode node) {
if (node == null) {
return 0;
}
int leftHeight = dG(node.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = dG(node.right);
if (rightHeight == -1) {
return -1;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight,rightHeight) + 1;
}
}
解法二:迭代法
①层序遍历求每个节点的高度
②比较每个节点的左右子树高度
// 暴力迭代
// 1.求子树高度 (因为root节点的深度和叶子节点的高度是一样,所以直接求root节点的深度了)
static public int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int height = 0;
while (!queue.isEmpty()) {
int size = queue.size();
height++;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return height;
}
//2.比较左右节点的子树高度
static public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || pre == root.right) {
if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1) {
return false;
}
pre = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return true;
}