Skip to content

Commit cf0f822

Browse files
author
Partho Biswas
committed
124_Binary_Tree_Maximum_Path_Sum
1 parent 2d7ce08 commit cf0f822

File tree

6 files changed

+230
-1
lines changed

6 files changed

+230
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
428428
|10| [105. Construct Binary Tree from Preorder and Inorder Traversal](https://tinyurl.com/y4s62xbu)| [Python](https://tinyurl.com/wu6rdaw/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py)| [Art 1](https://tinyurl.com/y3megvpm), [Art 2](https://tinyurl.com/tazaoyz), [Vid 1](https://tinyurl.com/qoqdsqv) | Medium | DFS, Very Important |
429429
|11| [106. Construct Binary Tree from Inorder and Postorder Traversal](https://tinyurl.com/yx78og6g)| [Python](https://tinyurl.com/wu6rdaw/106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py), [Swift](https://tinyurl.com/wuja3c4/106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.swift) | [Art 1](https://tinyurl.com/vlntqrp) | Medium | DFS, Very Important |
430430
|12| **[889. Construct Binary Tree from Preorder and Postorder Traversal](https://tinyurl.com/y578ty5u)** | [Python](https://tinyurl.com/wu6rdaw/889_Construct_Binary_Tree_from_Preorder_and_Postorder_Traversal.py)| [Vid 1](https://tinyurl.com/r6d4ym5), **[Art 1](https://tinyurl.com/tflqhp9)**, [Art 2](https://tinyurl.com/wkq7qyu) | Medium | 📌 **TODO: Check again. Important** |
431-
|13| **[124. Binary Tree Maximum Path Sum](https://tinyurl.com/yycvxmmy)**| [Python](https://tinyurl.com/wu6rdaw/124_Binary_Tree_Maximum_Path_Sum.py)| [Art 1](https://tinyurl.com/uocr9np), [Art 2](https://tinyurl.com/s23sqhe), [Vid 1](https://tinyurl.com/wwe95qx), [AlgoExpert](https://tinyurl.com/vofbonm) | Very Hard | **Very important and tricky** |
431+
|13| **[124. Binary Tree Maximum Path Sum](https://tinyurl.com/yycvxmmy)**| [Python](https://tinyurl.com/wu6rdaw/124_Binary_Tree_Maximum_Path_Sum.py), [Swift](https://tinyurl.com/wuja3c4/124_Binary_Tree_Maximum_Path_Sum.swift) | [Art 1](https://tinyurl.com/uocr9np), [Art 2](https://tinyurl.com/s23sqhe), [Vid 1](https://tinyurl.com/wwe95qx), [AlgoExpert](https://tinyurl.com/vofbonm) | Very Hard | **Very important and tricky** |
432432
|14| **[979. Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree/)**| [Python](https://tinyurl.com/wu6rdaw/979_Distribute_Coins_in_Binary_Tree.py)| [Art 1](https://tinyurl.com/rugoa38), [Art 2](https://tinyurl.com/whkdbl4), [Art 3](https://tinyurl.com/s62fws7) | Medium | **Very important. Postorder DFS** |
433433
|15| [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| [Python](https://tinyurl.com/wu6rdaw/116_Populating_Next_Right_Pointers_in_Each_Node.py)| [Art 1](https://tinyurl.com/t6p8kjb), [Art 2](https://tinyurl.com/ujzrhkj), **[Art 3](https://tinyurl.com/unrow77)** | Medium | BFS/DFS, Level order traversal |
434434
|16| [117. Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| [Python](https://tinyurl.com/wu6rdaw/117_Populating_Next_Right_Pointers_in_Each_Node_II.py)| [Vid 1](https://tinyurl.com/rfjhzj3), [Vid 2](https://tinyurl.com/ryghj42) | Medium | **Very tricky, check again** |
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import Foundation
2+
/**
3+
* Definition for a binary tree node.
4+
* public class TreeNode {
5+
* public var val: Int
6+
* public var left: TreeNode?
7+
* public var right: TreeNode?
8+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
9+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
10+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
11+
* self.val = val
12+
* self.left = left
13+
* self.right = right
14+
* }
15+
* }
16+
*/
17+
class Solution {
18+
func maxPathSum(_ root: TreeNode?) -> Int {
19+
var maxSumResult: Int = Int.min
20+
maxPathSumDFSHelper(root, &maxSumResult)
21+
return maxSumResult
22+
}
23+
24+
private func maxPathSumDFSHelper(_ root: TreeNode?, _ maxSumResult: inout Int) -> Int {
25+
guard let root = root else {
26+
return 0
27+
}
28+
let leftMaxSum = maxPathSumDFSHelper(root.left, &maxSumResult)
29+
let rightMaxSum = maxPathSumDFSHelper(root.right, &maxSumResult)
30+
31+
maxSumResult = [maxSumResult, root.val, root.val + leftMaxSum, root.val + rightMaxSum, root.val + leftMaxSum + rightMaxSum].max()!
32+
33+
return [root.val, root.val + leftMaxSum, root.val + rightMaxSum].max()!
34+
}
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import Foundation
2+
3+
// BruteForce. Time: O(arrayLen*3^steps). TLE. 12 / 31 test cases passed.
4+
class Solution {
5+
func numWays(_ steps: Int, _ arrLen: Int) -> Int {
6+
var totalWays = 0
7+
numWaysDFSHelper(steps, arrLen, 0, 1, &totalWays)
8+
return totalWays
9+
}
10+
11+
private func numWaysDFSHelper(_ steps: Int, _ arrLen: Int, _ currentIndex: Int, _ currentSteps: Int, _ totalWays: inout Int) {
12+
if currentSteps > steps {
13+
if currentIndex == 0 {
14+
totalWays += 1
15+
totalWays = totalWays % (Int(pow(Double(10), Double(9))) + 7)
16+
}
17+
return
18+
}
19+
20+
for i in [0, -1, 1] {
21+
let newIndex = currentIndex + i
22+
if newIndex >= 0 && newIndex < arrLen {
23+
numWaysDFSHelper(steps, arrLen, newIndex, currentSteps + 1, &totalWays)
24+
}
25+
}
26+
}
27+
}
28+
29+
// BruteForce with memoization. Time: O(arrayLen*3^steps).
30+
class Solution {
31+
func numWays(_ steps: Int, _ arrLen: Int) -> Int {
32+
var memo = [String:Int]()
33+
numWaysDFSHelper(steps, arrLen, 0, 1, &memo)
34+
print(memo)
35+
return memo["0-0"] ?? 0
36+
}
37+
38+
private func numWaysDFSHelper(_ steps: Int, _ arrLen: Int, _ currentIndex: Int, _ currentSteps: Int, _ memo: inout [String:Int]) {
39+
if let totalwaysFromMemo = memo["\(currentIndex)-\(steps - currentSteps)"] {
40+
memo["\(currentIndex)-\(steps - currentSteps)"] = totalwaysFromMemo + 1
41+
return
42+
}
43+
if currentSteps > steps {
44+
if currentIndex == 0 {
45+
if let totalwaysFromMemo = memo["0-0"] {
46+
memo["0-0"] = (totalwaysFromMemo + 1) % (Int(pow(Double(10), Double(9))) + 7)
47+
} else {
48+
memo["0-0"] = 1
49+
}
50+
}
51+
return
52+
}
53+
54+
for i in [0, -1, 1] {
55+
let newIndex = currentIndex + i
56+
if newIndex >= 0 && newIndex < arrLen && newIndex <= steps {
57+
if let totalwaysFromMemo = memo["\(newIndex)-\(steps - currentSteps - 1)"] {
58+
memo["\(newIndex)-\(steps - currentSteps - 1)"] = totalwaysFromMemo + 1
59+
} else {
60+
numWaysDFSHelper(steps, arrLen, newIndex, currentSteps + 1, &memo)
61+
memo["\(newIndex)-\(steps - currentSteps - 1)"] = totalwaysFromMemo + 1
62+
}
63+
}
64+
}
65+
}
66+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import Foundation
2+
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+
func str2tree(_ s: String) -> TreeNode? {
18+
guard s.count > 0, var str: [Character] = Array(s) else {
19+
return nil
20+
}
21+
var currentIndex = 0
22+
return str2treeDFSHelper(str, &currentIndex)
23+
}
24+
25+
private func str2treeDFSHelper(_ strArr: [Character], _ currentIndec: inout Int) -> TreeNode? {
26+
guard currentIndec < strArr.count else {
27+
return nil
28+
}
29+
30+
print("Index: \(currentIndec), value: \(strArr[currentIndec].wholeNumberValue)")
31+
var currentNodeVal: Int = strArr[currentIndec].wholeNumberValue!
32+
currentIndec += 1
33+
while currentIndec < strArr.count {
34+
if strArr[currentIndec].isWholeNumber {
35+
currentNodeVal = currentNodeVal*10 + strArr[currentIndec].wholeNumberValue!
36+
currentIndec += 1
37+
} else {
38+
break
39+
}
40+
}
41+
42+
var currentNode: TreeNode = TreeNode(currentNodeVal)
43+
if String(strArr[currentIndec]) == "(" {
44+
currentIndec += 1
45+
var left: TreeNode? = str2treeDFSHelper(strArr, &currentIndec)
46+
currentNode.left = left
47+
48+
currentIndec += 1
49+
var right: TreeNode? = str2treeDFSHelper(strArr, &currentIndec)
50+
currentNode.right = right
51+
} else if String(strArr[currentIndec]) == ")" {
52+
return currentNode
53+
}
54+
55+
56+
return currentNode
57+
}
58+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import Foundation
2+
3+
class ExamRoom {
4+
var n = 1
5+
var occupiedSeates = Set<Int>()
6+
var maxIntervalHeap = [Int]() // A max Heap of interval value
7+
var maxIntervalRangeMap = [Int:[(Int, Int)]]() // key = max interval, value = lower and upper range of the interval
8+
9+
init(_ N: Int) {
10+
self.n = N
11+
}
12+
13+
func seat() -> Int {
14+
if occupiedSeates.count <= 0 {
15+
occupiedSeates.insert(0)
16+
return 0
17+
} else {
18+
19+
}
20+
}
21+
22+
func leave(_ p: Int) {
23+
occupiedSeates.remove(p)
24+
25+
}
26+
}
27+
28+
/**
29+
* Your ExamRoom object will be instantiated and called as such:
30+
* let obj = ExamRoom(N)
31+
* let ret_1: Int = obj.seat()
32+
* obj.leave(p)
33+
*/
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,39 @@
11
import Foundation
22

3+
import Foundation
4+
5+
class Solution {
6+
func restoreIpAddresses(_ s: String) -> [String] {
7+
let digits: [Int] = Array(s).compactMap { $0.wholeNumberValue }
8+
guard digits.count >= 4 else {
9+
return []
10+
}
11+
12+
var allAdress = [String]()
13+
restoreIpAddressesDFSHelper(digits, 0, [], &allAdress)
14+
return allAdress
15+
}
16+
17+
private func restoreIpAddressesDFSHelper(_ digits: [Int], _ currentIdx: Int, _ currentAdress: [Int], _ allAdress: inout [String]) {
18+
if currentIdx >= digits.count && currentAdress.count == 4 {
19+
var currentAddrStr = currentAdress.map { String($0) }.joined(separator: ".")
20+
if currentAddrStr.count == digits.count + 3 {
21+
allAdress.append(currentAddrStr)
22+
}
23+
return
24+
}
25+
if currentAdress.count > 4 || currentIdx >= digits.count || (currentAdress.count >= 3 && (digits[currentIdx...].count > 3 || Int(digits[currentIdx...].map { String($0) }.reduce("", +))! > 255)) {
26+
return
27+
}
28+
var currentNum = 0
29+
for i in currentIdx..<min(currentIdx + 3, digits.count) {
30+
currentNum = currentNum*10 + digits[i]
31+
if currentNum >= 0 && currentNum <= 255 {
32+
restoreIpAddressesDFSHelper(digits, i + 1, currentAdress + [currentNum], &allAdress)
33+
} else {
34+
break
35+
}
36+
}
37+
return
38+
}
39+
}

0 commit comments

Comments
 (0)