1. 程式人生 > >LeetCode--104--二叉樹的最大深度

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

col 節點 葉子 roo span assm 最長路徑 str node

問題描述:

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例:
給定二叉樹 [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

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