AcWing 72. 平衡二叉树
思路一:求每个节点的左右子树深度,根据深度差判断,直到叶子节点结束,效率不够高,每个节点都要用两次计算深度的递归函数
思路二:从叶子节点开始,计算深度差,一旦有深度差大于1的,就直接返回0,也不用管上面的深度是不是正确了,毕竟我们只需要true和false两种状态,省略了很多次深度的计算
思路二的代码
class Solution {
boolean balanced=true;
public boolean isBalanced(TreeNode root) {
getDepth(root);
return balanced;
}
int getDepth(TreeNode root){
if(root==null) return 0;
int left=getDepth(root.left);
if(!balanced) return 0;
int right=getDepth(root.right);
if(!balanced) return 0;
if(Math.abs(left-right)>1) {
balanced=false;
return 0;
}
return 1+Math.max(left,right);
}
}
发布于 2020-02-16
AcWing 72. Go 题解 平衡二叉树
Talke is cheap.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
return isBalan(root) != -1
}
func isBalan(root *TreeNode) int {
if root == nil {
return 0
}
left := isBalan(root.Left)
right := isBalan(root.Right)
if left == -1 || right == -1 || left - right > 1 || left - right < -1 {
return -1
}
if left > right {
return left + 1
}
return right + 1
}
发布于 2020-02-16
AcWing 72. 平衡二叉树
C++几行直接解决
算法
直接用高度h,平衡二叉树递归满足