leetcode(543). Diameter of Binary Tree

来源:互联网 发布:二小姐捏脸数据 编辑:程序博客网 时间:2024/06/05 12:15

problem

Given a binary tree, you need to compute the length of the diameter of
the tree. The diameter of a binary tree is the length of the longest
path between any two nodes in a tree. This path may or may not pass
through the root.

分析

这个问题就是找到一棵二叉树中两个节点之间最远的距离,其实也就是对任意的节点左右两棵子树深度的和的最大值,因此这里只要对求树的深度的代码做一点修改即可。

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    #self要定义在有self的地方    def diameterOfBinaryTree(self, root):        """        :type root: TreeNode        :rtype: int        """        self.best = 0        def depth(r):            if r == None:                return 0            else:                l = depth(r.left)                r = depth(r.right)                self.best = max(self.best, l+r)                return 1 + max(l, r)        depth(root)        return self.best

总结

这个问题让我学会更加灵活的运用了递归算法,也就是利用递归算法的中间值l = depth(r.left),r = depth(r.right), self.best = max(self.best, l+r) ,使用中间值修改全局变量进行记录,这样时间复杂度不变却增加了一个遍历的功能,获得每个节点的左右子树深度。

note:
这样的应用通常都是原问题与递归问题有一定联系,例如这里原问题是所有节点的左右子树深度和的最大值,递归问题是求树的深度,所以在递归中就会求到所有节点为根的树的深度,这样就将两个问题联系了起来。