diameter-of-bt py3
This commit is contained in:
parent
713154644b
commit
cccdd9269f
27
0543_diameter-of-binary-tree/README.md
Normal file
27
0543_diameter-of-binary-tree/README.md
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
Given the `root` of a binary tree, return _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`.
|
||||||
|
|
||||||
|
The **length** of a path between two nodes is represented by the number of edges between them.
|
||||||
|
|
||||||
|
**Example 1:**
|
||||||
|
|
||||||
|
![](https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg)
|
||||||
|
|
||||||
|
Input: root = [1,2,3,4,5]
|
||||||
|
Output: 3
|
||||||
|
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
|
||||||
|
|
||||||
|
|
||||||
|
**Example 2:**
|
||||||
|
|
||||||
|
Input: root = [1,2]
|
||||||
|
Output: 1
|
||||||
|
|
||||||
|
|
||||||
|
**Constraints:**
|
||||||
|
|
||||||
|
* The number of nodes in the tree is in the range `[1, 104]`.
|
||||||
|
* `-100 <= Node.val <= 100`
|
||||||
|
|
||||||
|
https://leetcode.com/problems/diameter-of-binary-tree/
|
36
0543_diameter-of-binary-tree/python3/solution.py
Normal file
36
0543_diameter-of-binary-tree/python3/solution.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
# Definition for a binary tree node.
|
||||||
|
# class TreeNode:
|
||||||
|
# def __init__(self, val=0, left=None, right=None):
|
||||||
|
# self.val = val
|
||||||
|
# self.left = left
|
||||||
|
# self.right = right
|
||||||
|
class Solution:
|
||||||
|
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
|
||||||
|
result = [0]
|
||||||
|
|
||||||
|
def dfs(node):
|
||||||
|
# Leaf node height will be 1
|
||||||
|
# Empty node height will be -1
|
||||||
|
|
||||||
|
if node is None: return -1
|
||||||
|
|
||||||
|
lefth = dfs(node.left)
|
||||||
|
righth = dfs(node.right)
|
||||||
|
|
||||||
|
# Diameter calc:
|
||||||
|
#
|
||||||
|
# Cause for current node will be pointing to both
|
||||||
|
# left and right nodes and we need to consider
|
||||||
|
# them (+2)
|
||||||
|
#
|
||||||
|
# e.g. consider this is leaf node, lefth and righth = -1
|
||||||
|
# so, current node's diameter should be 0 = 2 + -1 + -1
|
||||||
|
result[0] = max(result[0], 2 + lefth + righth)
|
||||||
|
|
||||||
|
# return max height including the node itself
|
||||||
|
return 1 + max(lefth, righth)
|
||||||
|
|
||||||
|
dfs(root)
|
||||||
|
|
||||||
|
return result[0]
|
||||||
|
|
Loading…
Reference in New Issue
Block a user