Python实现二叉树的深度

python实现二叉树的深度搜索

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def isBalanced(self, root):
        if root==None:
            return 0
        leftheight=self.isBalanced(root.left)
        rightheight=self.isBalanced(root.right)
        if leftheight>=rightheight:
            return leftheight+1
        else:
            return rightheight+1



input_3=TreeNode(3)
input_4=TreeNode(4)
input_5 = TreeNode(5)
input_5.left=input_3
input_5.right=input_4
input_18 = TreeNode(18)
input_all = TreeNode(2)
input_all.left = input_5
input_all.right = input_18
slu_ = Solution()
print input_all
t = slu_.isBalanced(input_all)
print t


猜你喜欢

转载自blog.csdn.net/hguo11/article/details/73633217