设为首页 加入收藏

TOP

平衡二叉树(二叉树深度+DFS)
2017-02-08 08:16:49 】 浏览:1033
Tags:平衡 深度 DFS

题目描述


输入一棵二叉树,判断该二叉树是否是平衡二叉树。


平衡二叉树:又称AVL树,


具有如下性质:


它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树(即每一个结点的左右子树)。


# -*- coding:utf-8 -*-
# class TreeNode:
#? ? def __init__(self, x):
#? ? ? ? self.val = x
#? ? ? ? self.left = None
#? ? ? ? self.right = None
class Solution:
? ? def IsBalanced_Solution(self, pRoot):
? ? ? ? # write code here
? ? ? ? if pRoot is None:
? ? ? ? ?return True


? ? ? ? def DFS(root):


? ? ? ? ?# 如果说当前结点为None,返回0
? ? ? ? ?if not root:
? ? ? ? ? return 0
? ? ? ? ?# 返回左子树和右子树的最大值加1
? ? ? ? ?return max(DFS(root.right), DFS(root.left)) + 1


? ? ? ? h1 = DFS(pRoot.right)
? ? ? ? h2 = DFS(pRoot.left)
? ? ? ? # 如果说不满足平衡二叉树的性质,返回False
? ? ? ? if abs(h1 - h2) > 1:
? ? ? ? ?return False
? ? ? ? # 继续判断左子树和右子树是否满足二叉树的性质
? ? ? ? return self.IsBalanced_Solution(pRoot.right) and self.IsBalanced_Solution(pRoot.left)


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇按之字形顺序打印二叉树(二叉树的.. 下一篇Linux下进程编程入门笔记

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目