From cccdd9269f0850e7c0b5be095065f462114ca2c2 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Mon, 25 Apr 2022 12:55:17 +0530 Subject: [PATCH] diameter-of-bt py3 --- 0543_diameter-of-binary-tree/README.md | 27 ++++++++++++++ .../python3/solution.py | 36 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 0543_diameter-of-binary-tree/README.md create mode 100644 0543_diameter-of-binary-tree/python3/solution.py diff --git a/0543_diameter-of-binary-tree/README.md b/0543_diameter-of-binary-tree/README.md new file mode 100644 index 0000000..b0823ae --- /dev/null +++ b/0543_diameter-of-binary-tree/README.md @@ -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/ \ No newline at end of file diff --git a/0543_diameter-of-binary-tree/python3/solution.py b/0543_diameter-of-binary-tree/python3/solution.py new file mode 100644 index 0000000..2510967 --- /dev/null +++ b/0543_diameter-of-binary-tree/python3/solution.py @@ -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] + \ No newline at end of file