Open Ni-Guvara opened 1 year ago
迭代求深度, 递归判断平衡二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int leftDepth = depth(root.left);
int rightDepth = depth(root.right);
if(Math.abs(leftDepth - rightDepth) > 1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
int depth(TreeNode root){
if(root == null) return 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ans = 0;
while(!queue.isEmpty()){
ans++;
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode cur = queue.poll();
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
}
return ans;
}
}