543. binary tree diameter leetcode

Description of the problem

Given a binary tree, you need to calculate the length of its diameter. A binary tree is the maximum length of the diameter of any two nodes in the path lengths. This path may pass through the root.

Example:
given binary tree
where the code is inserted sheet

 		  1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the path length [4,2,1,3] or [5,2,1,3].

Note: the path length between two nodes is represented by the number of edges therebetween.

2 solution to a problem - recursion

Reference answers chiefs also encountered the same problem, start a direct count depth on both sides, then both sides of the root sum

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if not root:
            return 0
        
        return self.get_height(root.left) + self.get_height(root.right) 
    
    def get_height(self, root):
        if not root:
            return 0
        return max(self.get_height(root.left), self.get_height(root.right)) + 1


A wrong use cases:

[4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2]

Visualization look like

Here Insert Picture Description
The truth
Here Insert Picture Description
I have a need to preserve the value of this every time I compare the updated value of the maximum diameter, with self.max 0 = to initialize the value
when the value obtained each time a node of the left subtree and right subtree, have need to compare the size of the height of the right subtree, save more self.max and left sub-tree height + down
and then ask how the left subtree and right subtree height of it, that is the height of the classic recursion problem: max ( depth (root.left), depth (root.right )) + 1

class Solution:
    def __init__(self):
        self.max_diameter=0
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.depth(root)
        return self.max_diameter
    def depth(self,root:TreeNode):
        if not root:
            return 0
        l=self.depth(root.left)
        r=self.depth(root.right)
        self.max_diameter=max(self.max_diameter,l+r)
        return max(l,r)+1

Here Insert Picture Description
Here Insert Picture Description

Published 284 original articles · won praise 19 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_39289876/article/details/104776023