Skip to content

Commit 1b402b3

Browse files
author
Partho Biswas
committed
1305_All_Elements_in_Two_Binary_Search_Trees
1 parent dc54824 commit 1b402b3

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
463463
|39| [1315. Sum of Nodes with Even-Valued Grandparent](https://tinyurl.com/y72q6hfn) | [Python](https://tinyurl.com/wu6rdaw/1315_Sum_of_Nodes_with_Even_Valued_Grandparent.py), [Swift](https://tinyurl.com/wuja3c4/1315_Sum_of_Nodes_with_Even_Valued_Grandparent.swift) | -- | Medium | -- |
464464
|40| [129. Sum Root to Leaf Numbers](https://tinyurl.com/yaxakdfs) | [Python](https://tinyurl.com/wu6rdaw/129_Sum_Root_to_Leaf_Numbers.py), [Swift](https://tinyurl.com/wuja3c4/129_Sum_Root_to_Leaf_Numbers.swift) | -- | Medium | -- |
465465
|41| [938. Range Sum of BST](https://tinyurl.com/r43zu3p) | [Python](https://tinyurl.com/wu6rdaw/938_Range_Sum_of_BST.py), [Swift](https://tinyurl.com/wuja3c4/938_Range_Sum_of_BST.swift) | -- | Medium | -- |
466+
|42| [1305. All Elements in Two Binary Search Trees](https://tinyurl.com/undhmra) | [Python](https://tinyurl.com/wu6rdaw/1305_All_Elements_in_Two_Binary_Search_Trees.py), [Swift](https://tinyurl.com/wuja3c4/1305_All_Elements_in_Two_Binary_Search_Trees.swift) | -- | Medium | -- |
466467

467468
</p>
468469
</details>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
// Iterative inorder DFS
17+
class Solution {
18+
func getAllElements(_ root1: TreeNode?, _ root2: TreeNode?) -> [Int] {
19+
var (result, stack1, stack2) = ([Int](), [TreeNode](), [TreeNode]())
20+
var (currentNode1, currentNode2) = (root1, root2)
21+
22+
while (!stack1.isEmpty || currentNode1 != nil) || (!stack2.isEmpty || currentNode2 != nil) {
23+
while let node1 = currentNode1 {
24+
stack1.append(node1)
25+
currentNode1 = node1.left
26+
}
27+
28+
while let node2 = currentNode2 {
29+
stack2.append(node2)
30+
currentNode2 = node2.left
31+
}
32+
33+
if stack2.isEmpty || !stack1.isEmpty && (stack2.last!.val >= stack1.last!.val) {
34+
currentNode1 = stack1.removeLast()
35+
result.append(currentNode1!.val)
36+
currentNode1 = currentNode1!.right
37+
} else {
38+
currentNode2 = stack2.removeLast()
39+
result.append(currentNode2!.val)
40+
currentNode2 = currentNode2!.right
41+
}
42+
}
43+
return result
44+
}
45+
}

0 commit comments

Comments
 (0)