[Leetcode] 543. Diameter of Binary Tree 二叉树的直径

思路

  1. test cases: the path with the longest length may go through the root, or it may be in left subtree or right subtree without going through the root
  2. based on the test cases, we need to check the diameter of each node we meet
  3. time complexity: O(n), space complexity: O(n) stack space

方法1:divide-and-conquer, use global variable

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if root is None:
            return 0
        self.longest = 0
        self.dfs(root)
        return self.longest
    
    def dfs(self, root):
        if root is None:
            return 0, 0
        lleft, lright = self.dfs(root.left)
        rleft, rright = self.dfs(root.right)
        left = max(lleft, lright) + 1
        right = max(rleft, rright) + 1
        self.longest = max(self.longest, left + right - 2)
        return left, right

方法2:use divide-and-conquer, longest length is in the return values

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if root is None:
            return 0
        _, _, longest = self.dfs(root)
        return longest
    
    def dfs(self, root):
        if root is None:
            return 0, 0, 0
        lleft, lright, llongest = self.dfs(root.left)
        rleft, rright, rlongest = self.dfs(root.right)
        left = max(lleft, lright) + 1
        right = max(rleft, rright) + 1
        longest = max(llongest, rlongest, left + right - 2)
        return left, right, longest

你可能感兴趣的:(algorithm,二叉树,leetcode,dfs,算法)