forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 2
/
DiameterBinaryTree.swift
39 lines (32 loc) · 989 Bytes
/
DiameterBinaryTree.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Question Link: https://leetcode.com/problems/diameter-of-binary-tree/
* Primary idea: recursion, update globel diameter along with maxDepth
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class DiameterBinaryTree {
var diameter = 0
func diameterOfBinaryTree(_ root: TreeNode?) -> Int {
maxDepth(root)
return diameter
}
fileprivate func maxDepth(_ node: TreeNode?) -> Int {
guard let node = node else {
return 0
}
let (left, right) = (maxDepth(node.left), maxDepth(node.right))
diameter = max(diameter, left + right)
return max(left, right) + 1
}
}