二叉树的深度、二叉平衡树

【题目】
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:
递归调用
case1:当前节点有左右子树,则树的深度为左右子树最大值加1
case2:当前节点只有右子树,则树的深度为左子树加1
case3:当前节点只有左子树,则树的深度为右子树加1
递归出口:
树为空,return 0
当前节点为叶节点:
return 1
代码:

# 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==None:
            return 0
        if pRoot.left==None and pRoot.right==None:
            return 1
        #左右子树都不为空
        if pRoot.left!=None and pRoot.right!=None:
            return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
        #右子树为空
        elif pRoot.right==None:
            return self.TreeDepth(pRoot.left)+1
        #左子树为空
        else:
            return self.TreeDepth(pRoot.right)+1

调用树的深度函数,递归判断左右子树是否都满足高度差不超过1
代码:

# 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==None:
            return 0
        if pRoot.left==None and pRoot.right==None:
            return 1
        #左右子树都不为空
        if pRoot.left!=None and pRoot.right!=None:
            return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
        #右子树为空
        elif pRoot.right==None:
            return self.TreeDepth(pRoot.left)+1
        #左子树为空
        else:
            return self.TreeDepth(pRoot.right)+1
    def IsBalanced_Solution(self, pRoot):
        # write code here
        if pRoot == None:
            return True
        if abs(self.TreeDepth(pRoot.left)-self.TreeDepth(pRoot.right))>1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
        return True

你可能感兴趣的:(二叉树的深度、二叉平衡树)