java非递归平衡二叉树
时间: 2023-11-01 13:57:28 浏览: 67
在Java中,可以使用非递归的方法来判断一个二叉树是否是平衡二叉树。一种常用的方法是使用栈来进行遍历。具体的实现如下所示:
```java
import java.util.Stack;
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
int leftDepth = depth(cur.left);
int rightDepth = depth(cur.right);
if (Math.abs(leftDepth - rightDepth) > 1) {
return false;
}
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
return true;
}
private int depth(TreeNode node) {
if (node == null) return 0;
int leftDepth = depth(node.left);
int rightDepth = depth(node.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
```