File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments