# 39 平衡二叉树（深度+非递归/递归+后序）

import java.util.*;
public class Solution {
public int _Depth_Solution(TreeNode root) {
if(root == null)
return 0;
int left = _Depth_Solution(root.left) + 1;
int right = _Depth_Solution(root.right) + 1;
return (left > right) ? left : right;
}
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
Stack<TreeNode> stack = new Stack();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
int l = _Depth_Solution(cur.left);
int r = _Depth_Solution(cur.right);
if(Math.abs(l-r) > 1)
return false;
if(cur.right != null)
stack.push(cur.right);
if(cur.left != null)
stack.push(cur.left);

}
return true;
}
}

import java.util.*;
public class Solution {
public int _Depth_Solution(TreeNode root) {
if(root == null)
return 0;
int left = _Depth_Solution(root.left) + 1;
int right = _Depth_Solution(root.right) + 1;
return (left > right) ? left : right;
}
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
int l = _Depth_Solution(root.left);
int r = _Depth_Solution(root.right);
if(Math.abs(l-r) > 1)
return false;
return IsBalanced_Solution(root.left)&& IsBalanced_Solution(root.right);
}
}

import java.util.*;
public class Solution {
public boolean _IsBalanced_Solution(TreeNode root,int[] depth) {
if(root == null){
depth[0] = 0;
return true;
}
int[] left = new int[1],right = new int[1];
if(_IsBalanced_Solution(root.left,left) && _IsBalanced_Solution(root.right,right)){
if(Math.abs(left[0] - right[0]) <= 1){
depth[0] = ((left[0] > right[0]) ? left[0] : right[0]) + 1;
return true;
}
}
return false;
}
public boolean IsBalanced_Solution(TreeNode root) {
int[] depth = new int[1];
return _IsBalanced_Solution(root,depth);
}
}

  private boolean _IsBalanced_Solution(TreeNode root, int[] depth) {
if(root == null){
depth[0] = 0;
return true;
}
int[] leftDepth = new int[1],rightDepth = new int[1];
boolean leftB = _IsBalanced_Solution(root.left,leftDepth);
boolean rightB = _IsBalanced_Solution(root.right,rightDepth);
if(leftB && rightB){
depth[0] = ((leftDepth[0] > rightDepth[0]) ?
leftDepth[0] : rightDepth[0]);
return  true;
}
return false;
}

https://blog.csdn.net/abc7845129630/article/details/52744985
https://blog.csdn.net/Zheng548/article/details/65935030

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120