Skip to content

Commit bccdcc9

Browse files
committed
Adding 543. Diameter of Binary Tree in Swift
1 parent 8fa7d09 commit bccdcc9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public var val: Int
5+
* public var left: TreeNode?
6+
* public var right: TreeNode?
7+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
8+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
9+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
10+
* self.val = val
11+
* self.left = left
12+
* self.right = right
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
private var globalMaxDiameter: Int = 0
18+
19+
// Additionally, update the globalDiameter here
20+
func getMaxDepth(_ node: TreeNode?) -> Int {
21+
guard let node = node else { return 0 }
22+
23+
// compute for each child
24+
let leftMax = getMaxDepth(node.left)
25+
let rightMax = getMaxDepth(node.right)
26+
27+
// update diameter
28+
let diameter = leftMax + rightMax
29+
self.globalMaxDiameter = max(self.globalMaxDiameter, diameter)
30+
31+
// return max depth of 'this' node
32+
return 1 + max(leftMax, rightMax)
33+
}
34+
35+
func diameterOfBinaryTree(_ root: TreeNode?) -> Int {
36+
self.globalMaxDiameter = 0
37+
getMaxDepth(root)
38+
return self.globalMaxDiameter
39+
}
40+
}

0 commit comments

Comments
 (0)