【leetcode系列】【算法】【简单】二叉树的直径

题目:

题目链接: https://leetcode-cn.com/problems/diameter-of-binary-tree/

解题思路:

DFS搜索,对于某个根节点,查找左右子树的最高高度

左子树最大高度 + 右子树最大高度 + 1(自己) = 当前节点的最大半径

代码实现:

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

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if not root:
            return 0
        
        res = 0
        def dfs(root):
            nonlocal res
            if not root:
                return 0
            
            left_max_depth = dfs(root.left)
            right_max_depth = dfs(root.right)
            res = max(res, left_max_depth + right_max_depth + 1)
            print(res, root.val)
            return max(left_max_depth, right_max_depth) + 1
        
        dfs(root)
        return res - 1
发布了138 篇原创文章 · 获赞 13 · 访问量 2462

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105573043