LeetCode--104--二叉树的最大深度

问题描述:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / 
  9  20
    /  
   15   7

返回它的最大深度 3 。

方法1:

 1 class Solution(object):
 2     def maxDepth(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: int
 6         """
 7         if root == None:
 8             return 0
 9         def depth(self,root,ans):
10             if root == None:
11                 return ans
12             else:
13                 ans += 1    
14             ldepth = depth(self,root.left,ans)
15             rdepth = depth(self,root.right,ans)
16             if ldepth  > rdepth :
17                 return ldepth 
18             else:
19                 return rdepth
20         return depth(self,root,0) 

简体:

1 class Solution(object):
2     def maxDepth(self, root):
3         """
4         :type root: TreeNode
5         :rtype: int
6         """
7         if not root:
8             return 0
9         return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

简体2:

 1 class Solution(object):
 2     @classmethod
 3     def maxDepth(self, root):
 4         if root == None:
 5             return 0
 6 
 7         left =  Solution.maxDepth(root.left) +1
 8         right =  Solution.maxDepth(root.right) +1
 9 
10         return max(left, right) 

递归取左右子树高度的较大者

2018-09-07 20:21:23

原文地址:https://www.cnblogs.com/NPC-assange/p/9606854.html