剑指offer39 二叉树的深度

来源:互联网 发布:棋牌源码论坛 编辑:程序博客网 时间:2024/06/03 18:32

题目描述

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

思路

递归,深度为左子树和右子树最大深度加一

代码

# -*- coding:utf-8 -*-# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    def TreeDepth(self, pRoot):        # write code here        if pRoot == None:            return 0        left, right = 0, 0        if pRoot.left != None:            left = self.TreeDepth(pRoot.left)        if pRoot.right != None:            right = self.TreeDepth(pRoot.right)        return left + 1 if left > right else right + 1
原创粉丝点击