《剑指offer》二叉树的深度

本题来自《剑指offer》 二叉树的深度

题目:

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

思路:

   如果一棵树只有一个根节点,那么深度为1.

  如果一棵树只有左子树,没有右子树,那么应该在左子树上加1,同理右子树。

  如果左右子树都有子节点,那么选择左右子树最大节点,作为深度。

  所以采用递归的方式,调用,考虑边界条件的方式下,返回左右子树最大的节点深度作为结果值即可。

Python Code:

# -*- 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 not pRoot:                                        #the root node is empty
            return 0                                         #then return 0
        if pRoot and not pRoot.left and not pRoot.right:     #the root node and left node and right node is not empty
            return 1                                         #then return 1
        left = self.TreeDepth(pRoot.left)                    #recursively call the left node
        right = self.TreeDepth(pRoot.right)                  #recursively call the right node
        return max(left+1,right+1)                           #return the one of the max left and right

总结:

原文地址:https://www.cnblogs.com/missidiot/p/10783696.html