卖萌的弱渣

I am stupid, I am hungry.

Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example

Given a binary tree as follow:

1
2
3
4
5
  1
 / \ 
2   3
   / \
  4   5

The maximum depth is 3.

Solution

Time: O(n)

(Max-Depth-Binary-Tree.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    """
    @param root: The root of binary tree.
    @return: An integer
    """
    def maxDepth(self, root):
        # write your code here
        if root==None:
            return 0
        if root.left != None:
            left = self.maxDepth(root.left)
        else:
            left = 0
        if root.right != None:
            right = self.maxDepth(root.right)
        else:
            right = 0

        return max(left,right)+1