mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2602 from markwang1992/110-isBalanced
110.平衡二叉树增加Go迭代法
This commit is contained in:
@ -623,6 +623,8 @@ class Solution:
|
|||||||
```
|
```
|
||||||
### Go:
|
### Go:
|
||||||
|
|
||||||
|
递归法
|
||||||
|
|
||||||
```Go
|
```Go
|
||||||
func isBalanced(root *TreeNode) bool {
|
func isBalanced(root *TreeNode) bool {
|
||||||
h := getHeight(root)
|
h := getHeight(root)
|
||||||
@ -653,6 +655,64 @@ func max(a, b int) int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
迭代法
|
||||||
|
|
||||||
|
```Go
|
||||||
|
func isBalanced(root *TreeNode) bool {
|
||||||
|
st := make([]*TreeNode, 0)
|
||||||
|
if root == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
st = append(st, root)
|
||||||
|
for len(st) > 0 {
|
||||||
|
node := st[len(st)-1]
|
||||||
|
st = st[:len(st)-1]
|
||||||
|
if math.Abs(float64(getDepth(node.Left)) - float64(getDepth(node.Right))) > 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if node.Right != nil {
|
||||||
|
st = append(st, node.Right)
|
||||||
|
}
|
||||||
|
if node.Left != nil {
|
||||||
|
st = append(st, node.Left)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func getDepth(cur *TreeNode) int {
|
||||||
|
st := make([]*TreeNode, 0)
|
||||||
|
if cur != nil {
|
||||||
|
st = append(st, cur)
|
||||||
|
}
|
||||||
|
depth := 0
|
||||||
|
result := 0
|
||||||
|
for len(st) > 0 {
|
||||||
|
node := st[len(st)-1]
|
||||||
|
if node != nil {
|
||||||
|
st = st[:len(st)-1]
|
||||||
|
st = append(st, node, nil)
|
||||||
|
depth++
|
||||||
|
if node.Right != nil {
|
||||||
|
st = append(st, node.Right)
|
||||||
|
}
|
||||||
|
if node.Left != nil {
|
||||||
|
st = append(st, node.Left)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
st = st[:len(st)-1]
|
||||||
|
node = st[len(st)-1]
|
||||||
|
st = st[:len(st)-1]
|
||||||
|
depth--
|
||||||
|
}
|
||||||
|
if result < depth {
|
||||||
|
result = depth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### JavaScript:
|
### JavaScript:
|
||||||
|
|
||||||
递归法:
|
递归法:
|
||||||
|
Reference in New Issue
Block a user