Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1029 from Mahim1997/dev/543_swift
Browse files Browse the repository at this point in the history
543. Diameter of Binary Tree
  • Loading branch information
Ahmad-A0 authored Sep 5, 2022
2 parents a02b616 + bccdcc9 commit 07b4599
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions swift/543-Diameter-of-Binary-Tree.swift
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
}
}

0 comments on commit 07b4599

Please sign in to comment.