|
| 1 | +# 543. Diameter of Binary Tree |
| 2 | + |
| 3 | +## Best Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of nodes in binary tree |
| 7 | + |
| 8 | +Take this binary tree example: |
| 9 | +``` |
| 10 | + 1 |
| 11 | + / \ |
| 12 | + 2 3 |
| 13 | + / \ |
| 14 | +4 5 |
| 15 | +``` |
| 16 | + |
| 17 | +In the perspective of node 1, what do you need? |
| 18 | +- You will need to know what the current longest path found so far from either left or right is. |
| 19 | +- You will also need to know what the longest 'connectable' path is. |
| 20 | + |
| 21 | +Connectable path means taking your child's connectable path and connecting it with yourself, hence, creating a long chain. |
| 22 | +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. |
| 24 | + |
| 25 | +``` |
| 26 | +class Solution: |
| 27 | + 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 |
| 39 | + if root is None: |
| 40 | + return 0 |
| 41 | + longest_path, longest_connectable_path = length_helper(root) |
| 42 | + return longest_path-1 |
| 43 | +``` |
0 commit comments