543. Diameter of Binary 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.

idea:

For every node, length of longest path which pass it = MaxDepth of its left subtree + MaxDepth of its right subtree.

重點是 every node, 所以跟 104 不大一樣的點是, 104 也是求最大深度, 但這是整個的最大深度, 而這題是要最長的左深度 + 右深度, 所以在運算過程中, 要記錄最大的 left + right, 也就是可能不會經過 root, 就有最大diameter了

104 那種整個跑完, 求得整個樹的深度, 一定有經過 root

can refer:

https://ithelp.ithome.com.tw/articles/10227129

time: O(n)

space: O(n)

new ver

naive, we can do bfs on each node: O(n^2)

right ver, dfs

T: O(n)

S: O(h), worst O(n)

without global variable

Last updated

Was this helpful?