File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -623,6 +623,8 @@ class Solution:
623623```
624624### Go:
625625
626+ 递归法
627+
626628``` Go
627629func 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递归法:
You can’t perform that action at this time.
0 commit comments