二叉树节点间的最大距离问题

ぐ巨炮叔叔 提交于 2019-12-17 02:08:19

二叉树节点间的最大距离问题

求二叉树两节点间的最大距离(可能过根节点,也可能不过),LeetCode 543

思路

最大距离可能来自三种情况:

  • 根节点左子树上的最大距离
  • 根节点右子树上的最大距离
  • 左孩子最大深度ldepth,到根节点,到右孩子最大深度rdepth

实现1

    def max_distance(self):
        def post_order(node):
            if node is None:
                record[0] = 0
                return 0

            lmax = post_order(node.left)
            max_from_left = record[0]

            rmax = post_order(node.right)
            max_from_right = record[0]

            cur_max = max_from_left + max_from_right + 1
            record[0] = max(max_from_left, max_from_right) + 1

            return max(max(lmax, rmax), cur_max)

        if not self.root:
            return 0

        record = [0]
        return post_order(self.root) - 1

实现2

    def max_distance2(self):
        def depth(node):
            if not node:
                return 0

            ldepth = depth(node.left)
            rdepth = depth(node.right)
            result[0] = max(result[0], ldepth+rdepth+1)

            return max(ldepth, rdepth)+1

        result = [0]
        depth(self.root)
        return result[0] - 1

实现3

    def max_distance3(self):
        def depth(node):
            nonlocal result
            if not node:
                return 0

            ldepth = depth(node.left)
            rdepth = depth(node.right)
            result = max(result, ldepth+rdepth+1)

            return max(ldepth, rdepth)+1

        result = 0
        depth(self.root)
        return result - 1

测试

使用LeetCode测试:
实现1
实现3
实现2跟3相同。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!