Given a binary tree, you need to compute 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.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private var diameter = 0 private func diameterOfNode(_ root: TreeNode?) -> Int { var lv = 0, rv = 0 if let l = root?.left { lv = 1 + diameterOfNode(l) } if let r = root?.right { rv = 1 + diameterOfNode(r) } diameter = max(diameter, lv + rv) return max(lv, rv) } func diameterOfBinaryTree(_ root: TreeNode?) -> Int { diameterOfNode(root) return diameter } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼