首页 > 其他 > 详细

Leetcode_num2_Maximum Depth of Binary Tree

时间:2014-09-17 20:26:52      阅读:305      评论:0      收藏:0      [点我收藏+]

题目:

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.


AC率第二高的题啦,二项树的最长路径。初看此题就感觉要用递归,但不知怎的,一开始想到深度遍历上去了。。。。囧

实际上很简单的,某一节点的最长路径=max(该节点左子树的最长路径,该节点右子树的最长路径)+1

还有一点就是类中函数调用函数时格式为 self.函数名,否则会报 global name XXX is not defined

废话不多说啦,上代码咯

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

class Solution:
    # @param root, a tree node
    # @return an integer
    def maxDepth(self, root):
        if root==None:
            return 0
        else:
            p=max(self.maxDepth(root.left),self.maxDepth(root.right))+1
            return p


Leetcode_num2_Maximum Depth of Binary Tree

原文:http://blog.csdn.net/eliza1130/article/details/39347315

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!