forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#1029 from Mahim1997/dev/543_swift
543. Diameter of Binary Tree
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* 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 { | ||
private var globalMaxDiameter: Int = 0 | ||
|
||
// Additionally, update the globalDiameter here | ||
func getMaxDepth(_ node: TreeNode?) -> Int { | ||
guard let node = node else { return 0 } | ||
|
||
// compute for each child | ||
let leftMax = getMaxDepth(node.left) | ||
let rightMax = getMaxDepth(node.right) | ||
|
||
// update diameter | ||
let diameter = leftMax + rightMax | ||
self.globalMaxDiameter = max(self.globalMaxDiameter, diameter) | ||
|
||
// return max depth of 'this' node | ||
return 1 + max(leftMax, rightMax) | ||
} | ||
|
||
func diameterOfBinaryTree(_ root: TreeNode?) -> Int { | ||
self.globalMaxDiameter = 0 | ||
getMaxDepth(root) | ||
return self.globalMaxDiameter | ||
} | ||
} |