[LeetCode] 543. Diameter of Binary Tree / Swift
[문제 보기]
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:

Input: root = [1,2,3,4,5] Output: 3 Explanation: 3is 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, 10^4].
- -100 <= Node.val <= 100
https://leetcode.com/problems/diameter-of-binary-tree/
Diameter of Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이과정
이진트리의 노드간 가장 긴 경로의 길이를 구하는 문제였다. 여기서 가장 긴 경로는 루트 노드를 꼭 거치지 않아도 된다.
재귀를 이용해서 풀었다.
갱신은 현재까지의 탐색에서 최대의 길이합을, 반환은 두 자식중 어느쪽으로 갔을때 최대인지를 반환해서 계속해서 가장 긴 길이로 비교할 수 있게 했다.
이 문제를 마지막으로 top 100 liked의 easy문제를 모두 풀었다!!
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
var max = 0
func getDiameter(_ node: TreeNode?) -> Int {
let lv = node?.left == nil ? 0 : getDiameter(node?.left) + 1
let rv = node?.right == nil ? 0 : getDiameter(node?.right) + 1
if lv + rv > max {
max = lv + rv
}
return lv > rv ? lv : rv
}
func diameterOfBinaryTree(_ root: TreeNode?) -> Int {
getDiameter(root)
return max
}
}