Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2d62adc

Browse files
110.平衡二叉树增加Go迭代法
1 parent 3253a5c commit 2d62adc

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎problems/0110.平衡二叉树.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,8 @@ class Solution:
623623
```
624624
### Go:
625625

626+
递归法
627+
626628
```Go
627629
func isBalanced(root *TreeNode) bool {
628630
h := getHeight(root)
@@ -653,6 +655,64 @@ func max(a, b int) int {
653655
}
654656
```
655657

658+
迭代法
659+
660+
```Go
661+
func isBalanced(root *TreeNode) bool {
662+
st := make([]*TreeNode, 0)
663+
if root == nil {
664+
return true
665+
}
666+
st = append(st, root)
667+
for len(st) > 0 {
668+
node := st[len(st)-1]
669+
st = st[:len(st)-1]
670+
if math.Abs(float64(getDepth(node.Left)) - float64(getDepth(node.Right))) > 1 {
671+
return false
672+
}
673+
if node.Right != nil {
674+
st = append(st, node.Right)
675+
}
676+
if node.Left != nil {
677+
st = append(st, node.Left)
678+
}
679+
}
680+
return true
681+
}
682+
683+
func getDepth(cur *TreeNode) int {
684+
st := make([]*TreeNode, 0)
685+
if cur != nil {
686+
st = append(st, cur)
687+
}
688+
depth := 0
689+
result := 0
690+
for len(st) > 0 {
691+
node := st[len(st)-1]
692+
if node != nil {
693+
st = st[:len(st)-1]
694+
st = append(st, node, nil)
695+
depth++
696+
if node.Right != nil {
697+
st = append(st, node.Right)
698+
}
699+
if node.Left != nil {
700+
st = append(st, node.Left)
701+
}
702+
} else {
703+
st = st[:len(st)-1]
704+
node = st[len(st)-1]
705+
st = st[:len(st)-1]
706+
depth--
707+
}
708+
if result < depth {
709+
result = depth
710+
}
711+
}
712+
return result
713+
}
714+
```
715+
656716
### JavaScript:
657717

658718
递归法:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /