leetcode 104. Maximum Depth of Binary Tree

来源:互联网 发布:帝国cms 搜索代码 编辑:程序博客网 时间:2024/06/05 04:55
 leetcode  104. Maximum Depth of Binary Tree

#coding=utf-8
'''
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.

Subscribe to see which companies asked this question.
'''

这是看的别人的代码,易懂,可是自己第一次就是写不出来

#Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:return 0
        leftDepth = 1;rightDepth=1;
        if root.left!=None:
            leftDepth=leftDepth+self.maxDepth(root.left)
        if root.right!=None:
            rightDepth=rightDepth+self.maxDepth(root.right)
        return max(leftDepth,rightDepth)



#更简单的一个,思想和上面一样,只是写的简洁而已,不过这就是python的特点
     def findmaxDepth(self,root):
         if not root:return 0
         return 1+max(self.findmaxDepth(root.left),self.findmaxDepth(root.right))

#要想简洁这个也很简洁的,哈哈
     def maxDepth(self, root):
         return 0 if root is None else max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1



0 0