剑指offer-python

求二叉树的深度、判断是否为平衡二叉树

2018-08-28  本文已影响0人  小歪与大白兔

题目一:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if pRoot is None:
            return 0
        left = self.TreeDepth(pRoot.left)
        right = self.TreeDepth(pRoot.right)
        return max(left,right)+1

题目二
输入一棵二叉树,判断该二叉树是否是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它是一颗平衡二叉树。
思路一:
采用上一题计算深度的思路,调用TreeDepth得到左右子树的深度,判断其差值是否大于1 。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if pRoot is None:
            return 0
        left = self.TreeDepth(pRoot.left)
        right = self.TreeDepth(pRoot.right)
        return max(left,right)+1

    def IsBalanced_Solution(self, pRoot):
        # write code here
        if pRoot is None:
            return  True
        left = self.TreeDepth(pRoot.left)
        right = self.TreeDepth(pRoot.right)
        diff = abs(left-right)
        if diff > 1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
上一篇 下一篇

猜你喜欢

热点阅读