#-*- coding: UTF-8 -*-
#平衡二叉树
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
isbalanced=True
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root==None:return True
if root.left==None and root.right==None:return True
self.dfs(root)
return self.isbalanced
def dfsDepth(self,root):
if root==None:return 0
leftDepth=self.dfsDepth(root.left)
rightDepth=self.dfsDepth(root.right)
return leftDepth+1 if leftDepth >rightDepth else (rightDepth+1)
def dfs(self,root):
if root==None:return
leftDepth=self.dfsDepth(root.left)
rightDepth=self.dfsDepth(root.right)
if abs(leftDepth-rightDepth)>1:
self.isbalanced=False
else:
self.dfs(root.left)
self.dfs(root.right)
相关文章
- 02-29Leetcode 104. Maximum Depth of Binary Tree(二叉树的最大深度)
- 02-29LeetCode Binary Tree Preorder Traversal 先根遍历
- 02-29【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
- 02-29【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)
- 02-29LeetCode不定时刷题——Convert Sorted Array to Binary Search Tree
- 02-29LeetCode 199: Binary Tree Right Side View
- 02-29[leetcode-606-Construct String from Binary Tree]
- 02-29[LeetCode] 968. Binary Tree Cameras
- 02-29[LeetCode] 968. Binary Tree Cameras 二叉树相机
- 02-29【Leetcode】700. Search in a Binary Search Tree