Skip to content

Commit f73728d

Browse files
author
Joseph Luce
authored
Update 543_diameter_of_binary_tree.md
1 parent 86bb84e commit f73728d

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

leetcode/easy/543_diameter_of_binary_tree.md

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,35 @@ In the perspective of node 1, what do you need?
1818
- You will need to know what the current longest path found so far from either left or right is.
1919
- You will also need to know what the longest 'connectable' path is.
2020

21-
Connectable path means taking your child's connectable path and connecting it with yourself, hence, creating a long chain.
21+
Connectable path means taking your child's connectable path and connecting it with yourself, hence, creating a longer chain.
2222
This is completely separate from the curent longest path.
23-
You want to know if you can create a longer chain than the current longest path found so far.
23+
You want to know if you can create a longer chain than the current longest path found so far by adding the node you are currently on and the longest paths from the right and left that also include themselves as part of the chain.
2424

2525
```
2626
class Solution:
27+
def __init__(self):
28+
self.longest = 0
29+
2730
def diameterOfBinaryTree(self, root: TreeNode) -> int:
28-
def length_helper(root):
29-
if root is None:
30-
return 0, 0
31-
# Figure out the longest right and left
32-
# Then see if we can use either right or left to create a longer path
33-
longest_right, n_right_connectable_nodes = length_helper(root.right)
34-
longest_left, n_left_connectable_nodes = length_helper(root.left)
35-
n_connected_nodes = n_right_connectable_nodes + n_left_connectable_nodes + 1
36-
local_longest = max(longest_right, longest_left, n_connected_nodes)
37-
best_n_connectable_nodes = max(n_right_connectable_nodes+1, n_left_connectable_nodes+1)
38-
return local_longest, best_n_connectable_nodes
3931
if root is None:
4032
return 0
41-
longest_path, longest_connectable_path = length_helper(root)
42-
return longest_path-1
33+
longest_connectable_path = self._get_diameter_helper(root)
34+
return self.longest-1
35+
36+
def _get_diameter_helper(self, root):
37+
if root is None:
38+
return 0
39+
n_right_connectable_nodes = self._get_diameter_helper(root.right)
40+
n_left_connectable_nodes = self._get_diameter_helper(root.left)
41+
n_connected_nodes = n_right_connectable_nodes + n_left_connectable_nodes + 1
42+
self.longest = max(self.longest, n_connected_nodes)
43+
return max(n_right_connectable_nodes, n_left_connectable_nodes)+1
44+
```
45+
46+
# Follow-up Question
47+
Return instead the values of the nodes that are the longest.
48+
With the above example, return a list containing [4,2,1,3] and [5,2,1,3].
49+
50+
```
51+
4352
```

0 commit comments

Comments
 (0)