From 2d62adc079f920e0bea4abce8f209cc7507c633e Mon Sep 17 00:00:00 2001 From: markwang Date: Thu, 4 Jul 2024 15:50:30 +0800 Subject: [PATCH] =?UTF-8?q?110.=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E5=A2=9E=E5=8A=A0Go=E8=BF=AD=E4=BB=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index dd05bdd6..f8071333 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -623,6 +623,8 @@ class Solution: ``` ### Go: +递归法 + ```Go func isBalanced(root *TreeNode) bool { 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: 递归法: