mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
update 0110.平衡二叉树: 替换 go 代码
This commit is contained in:
@ -158,7 +158,7 @@ if (node == NULL) {
|
|||||||
|
|
||||||
如何判断以当前传入节点为根节点的二叉树是否是平衡二叉树呢?当然是其左子树高度和其右子树高度的差值。
|
如何判断以当前传入节点为根节点的二叉树是否是平衡二叉树呢?当然是其左子树高度和其右子树高度的差值。
|
||||||
|
|
||||||
分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则则返回-1,表示已经不是二叉平衡树了。
|
分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是二叉平衡树了。
|
||||||
|
|
||||||
代码如下:
|
代码如下:
|
||||||
|
|
||||||
@ -342,7 +342,7 @@ public:
|
|||||||
|
|
||||||
**例如:都知道回溯法其实就是递归,但是很少人用迭代的方式去实现回溯算法!**
|
**例如:都知道回溯法其实就是递归,但是很少人用迭代的方式去实现回溯算法!**
|
||||||
|
|
||||||
因为对于回溯算法已经是非常复杂的递归了,如果在用迭代的话,就是自己给自己找麻烦,效率也并不一定高。
|
因为对于回溯算法已经是非常复杂的递归了,如果再用迭代的话,就是自己给自己找麻烦,效率也并不一定高。
|
||||||
|
|
||||||
## 总结
|
## 总结
|
||||||
|
|
||||||
@ -559,37 +559,32 @@ class Solution:
|
|||||||
### Go
|
### Go
|
||||||
```Go
|
```Go
|
||||||
func isBalanced(root *TreeNode) bool {
|
func isBalanced(root *TreeNode) bool {
|
||||||
if root==nil{
|
h := getHeight(root)
|
||||||
return true
|
if h == -1 {
|
||||||
}
|
|
||||||
if !isBalanced(root.Left) || !isBalanced(root.Right){
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
LeftH:=maxdepth(root.Left)+1
|
|
||||||
RightH:=maxdepth(root.Right)+1
|
|
||||||
if abs(LeftH-RightH)>1{
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
func maxdepth(root *TreeNode)int{
|
// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1
|
||||||
if root==nil{
|
func getHeight(root *TreeNode) int {
|
||||||
|
if root == nil {
|
||||||
return 0
|
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{
|
func max(a, b int) int {
|
||||||
if a>b{
|
if a > b {
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
func abs(a int)int{
|
|
||||||
if a<0{
|
|
||||||
return -a
|
|
||||||
}
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### JavaScript
|
### JavaScript
|
||||||
|
Reference in New Issue
Block a user