From 6efc66e17597da3038966c690bb75dd4f0e61ad0 Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Sat, 5 Jun 2021 18:13:20 -0700 Subject: [PATCH] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 56 ++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 1cd54849..b9d01503 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -498,6 +498,62 @@ class Solution { Python: +> 递归法: +```python +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + return True if self.getDepth(root) != -1 else False + + #返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1 + def getDepth(self, node): + if not node: + return 0 + leftDepth = self.getDepth(node.left) + if leftDepth == -1: return -1 #说明左子树已经不是二叉平衡树 + rightDepth = self.getDepth(node.right) + if rightDepth == -1: return -1 #说明右子树已经不是二叉平衡树 + return -1 if abs(leftDepth - rightDepth)>1 else 1 + max(leftDepth, rightDepth) +``` + +> 迭代法: +```python +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + st = [] + if not root: + return True + st.append(root) + while st: + node = st.pop() #中 + if abs(self.getDepth(node.left) - self.getDepth(node.right)) > 1: + return False + if node.right: + st.append(node.right) #右(空节点不入栈) + if node.left: + st.append(node.left) #左(空节点不入栈) + return True + + def getDepth(self, cur): + st = [] + if cur: + st.append(cur) + depth = 0 + result = 0 + while st: + node = st.pop() + if node: + st.append(node) #中 + st.append(None) + depth += 1 + if node.right: st.append(node.right) #右 + if node.left: st.append(node.left) #左 + else: + node = st.pop() + depth -= 1 + result = max(result, depth) + return result +``` + Go: ```Go