diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 6e7c8c53..83e4dc4f 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -158,7 +158,7 @@ if (node == NULL) { 如何判断以当前传入节点为根节点的二叉树是否是平衡二叉树呢?当然是其左子树高度和其右子树高度的差值。 -分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则则返回-1,表示已经不是二叉平衡树了。 +分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是二叉平衡树了。 代码如下: @@ -342,7 +342,7 @@ public: **例如:都知道回溯法其实就是递归,但是很少人用迭代的方式去实现回溯算法!** -因为对于回溯算法已经是非常复杂的递归了,如果在用迭代的话,就是自己给自己找麻烦,效率也并不一定高。 +因为对于回溯算法已经是非常复杂的递归了,如果再用迭代的话,就是自己给自己找麻烦,效率也并不一定高。 ## 总结 @@ -559,37 +559,32 @@ class Solution: ### Go ```Go func isBalanced(root *TreeNode) bool { - if root==nil{ - return true - } - if !isBalanced(root.Left) || !isBalanced(root.Right){ - return false - } - LeftH:=maxdepth(root.Left)+1 - RightH:=maxdepth(root.Right)+1 - if abs(LeftH-RightH)>1{ + h := getHeight(root) + if h == -1 { return false } return true } -func maxdepth(root *TreeNode)int{ - if root==nil{ +// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1 +func getHeight(root *TreeNode) int { + if root == nil { return 0 } - return max(maxdepth(root.Left),maxdepth(root.Right))+1 + l, r := getHeight(root.Left), getHeight(root.Right) + if l == -1 || r == -1 { + return -1 + } + if l - r > 1 || r - l > 1 { + return -1 + } + return max(l, r) + 1 } -func max(a,b int)int{ - if a>b{ +func max(a, b int) int { + if a > b { return a } return b } -func abs(a int)int{ - if a<0{ - return -a - } - return a -} ``` ### JavaScript