Binary Tree Upside Down - swift

The output from my code return an empty array while trying to put a binary tree upside down using dfs recursion. How do I fix this ?
public class TreeNode {
var val :Int
var left: TreeNode?
var right: TreeNode?
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
func upsideDownBinaryTree(_ root: TreeNode?) -> TreeNode? {
return dfs(current: root)
}
func dfs( current: TreeNode?) -> TreeNode? {
if current == nil {
return nil
}
let newRoot = dfs(current: current?.left)
current?.left?.left = current?.right
current?.left?.right = current
current?.left = nil
current?.right = nil
return newRoot
}
}
enter image description here

The problem is at the base case of recursion: it will always return nil. Since any other returned value is exactly the same as what was retrieved from the recursive call (newRoot), it can never be anything else than nil. There is no way the function can return anything else than nil.
Realise that the case current == nil is only there to deal with an empty tree. In all other cases the recursion should stop one step earlier: when it is a node without left child. In that case that node should be returned.
So change:
if current == nil {
return nil
}
To:
if current?.left == nil {
return current
}
Now the base case is focussed on the non-presence of the left child, and in that case the node itself will be returned. The case where current itself is nil is only relevant when the tree is empty, but it is also covered here.

Related

Recursively find the parent of a node in tree

I have implemented a (non-binary) tree data structure like this:
class Node {
var id: String
var children: [Node] = []
}
To find a node with a given id as well as its parent, I have the following function:
extension Node {
func searchNodeAndParent(_ id: String, parentNode: Node) -> (Node?, Node?) {
if id == self.id {
return (self, nil)
}
for child in children {
if let found = child.searchNodeAndParent(id, parentNode: self).0 {
return (found, parentNode)
}
}
return (nil, nil)
}
}
However, I cannot seem to find the correct parent with rootNode.searchNodeAndParent(id, parentNode: nil). I suspect that self might not be the correct parent to use as the parameter, but do not know how I can fix it.
You keep returning the parentNode of the current node, instead of the one that one of the recursive functions may have found.
What you'd want to do is:
check if this node the one you want
for each child, start the recursion, passing self as the parent. If the recursion returns a non-nil result of (node, parent), return the tuple as-is.
Also, your return type should probably be: (Node, Node?)? - i.e. either the entire tuple is nil indicating a Not Found result, or if the tuple exists a parent could still be nil in the case of the root.
extension Node {
func searchNodeAndParent(_ id: String, parentNode: Node?) -> (Node, Node?)? {
if id == self.id {
return (self, parentNode) // create the found result here
}
for child in children {
if let found = child.searchNodeAndParent(id, parentNode: self) {
return found // return what was found as-is
}
}
return nil // nothing was found, the entire result is nil
}
}
Unrelated, but you might want to hide this method that takes in the parentNode parameter from the API surface (e.g. make it private), and give users a more convenient function that only takes the id as the parameter:
extension Node {
func searchNodeAndParent(_ id: String) -> (Node, Node?)? {
searchNodeAndParent(id, parentNode: nil)
}
private func searchNodeAndParent(_ id: String, parentNode: Node?) -> (Node, Node?)? {
// ...
}
}

How do you assign and unwrap an optional array object in Swift?

I'm trying to invert a binary tree in Swift using the iterative approach. Essentially I just keep looping through each node, and putting it into a stack array. This array should be an array of optional nodes. Here is my code:
func invertTree(_ root: TreeNode?) -> TreeNode? {
if root != nil {
stack.append(root)
} else {
return root
}
var stack = [TreeNode?]()
while stack.count > 0 {
if stack.last == nil {
stack.removeLast()
} else {
var tempLeft : TreeNode? = stack.last!.left
stack.last!.left = stack.last!.right
stack.last!.right = tempLeft
if stack.last!.left != nil {
stack.append(stack.last!.left)
}
if stack.last.right != nil {
stack.append(stack.last!.right)
}
}
}
return root
}
I'm getting all sorts of optional errors. In particular, when I set:
var tempLeft : TreeNode? = stack.last!.left
I'm not sure why it says "value of optional type TreeNode? must be unwrapped to refer to member 'left' of unwrapped base type 'TreeNode' in solution.swift"
I don't understand why it's telling me to unwrap the optional, when I'm already force unwrapping it. I don't want to unwrap the .left node since I want to include nils in my stack for the iteration to work.
Any help would be greatly appreciated.
stack.last is a doubly optional TreeNode: TreeNode??.
You could use optional chaining like so:
if stack.last == nil {
stack.removeLast()
} else {
stack.last
var tempLeft : TreeNode? = stack.last!?.left
stack.last!?.left = stack.last!?.right
stack.last!?.right = tempLeft
if stack.last!?.left != nil {
stack.append(stack.last!?.left)
}
if stack.last??.right != nil {
stack.append(stack.last!?.right)
}
}
Or avoid the drama and use pattern matching:
if case let node?? = stack.last {
let tempLeft = node.left
node.left = node.right
node.right = tempLeft
...
Other than that, it seems that there are other areas of your code that you need to tend to. For example, using stack before its declaration.
Alternative implementation
Here is a solution that uses a stack:
class Solution {
func invertTree(_ root: TreeNode?) -> TreeNode? {
guard let r = root else {
return nil
}
var stack = [r]
while let node = stack.last {
let temp = node.left
node.left = node.right
node.right = temp
stack.removeLast()
if let left = node.left { stack.append(left) }
if let right = node.right { stack.append(right) }
}
return r
}
}

Reverse a linked list in Swift

Reversing a linked list in Swift is easy. I have a working solution. However, while preparing for whiteboard interviews the version I produce quickly simply does not work and I cannot identify why.
I need to know why the following does not work - from the Playground I believe it is because
tail = previous
line errors and execution never completes.
func reverseLL (node: Node?) -> Node? {
guard node != nil else { return nil }
var tail : Node? = node
var previous = node?.next
while previous != nil {
let tailRef = previous?.next
previous?.next = tail
tail = previous
previous = tailRef
}
return tail
}
My definition of the linked list is:
class Node: CustomStringConvertible {
var data: Int
var next: Node?
var description: String {
return String(data) + (next != nil ? next!.description : "")
}
init (data: Int) {
self.data = data
next = nil
}
func appendToTail(data: Int) {
if (next != nil) {
next?.appendToTail(data: data)
}
else {
next = Node(data: data)
}
}
}
My working version of reverseLL (which I accept is more 'Swifty') is as follows, but I believe it should be functionally identical to my earlier definition.
func reverseLL (node: Node?) -> Node? {
guard node != nil else { return nil }
var tail: Node?
var headNode = node
while let head = headNode {
let tailRef = head.next
head.next = tail
tail = head
headNode = tailRef
}
return tail
}
So creating a linked list with
let ll = Node(data: 3)
ll.appendToTail(data: 4)
ll.appendToTail(data: 4)
ll.appendToTail(data: 5)
gives the data in order of 3445
and reversed through
reverseLL(node: ll)
gives the data in order of 5443
To be clear, why does the
tail = previous
line halt execution in my first definition of reverseLL?
The second version is more Swifty since you're using optional binding and avoiding the horrendous forced-unwrapping.
The problem in the first version is that tail is initially equal to node. In the example that you've given that is (3->4->4->5).
So when you do previous?.next = tail in the first iteration, previous becomes (4->4->5->3->4->5->3->4->5->...). Notice that The node with data equal to 5 now points to a node with data equal to 3. Which creates an infinite loop.
Simplification
The guard statement could also be written as :
guard node?.next != nil else {
return node
}
which would include lists with a single node.
Here is the complete code including class, function and input and output things
// First we are creating class to store the data of Linked List
class Node {
var data: Int
var next: Node?
var description: String {
return String(data) + (next != nil ? next!.description : "")
}
init (data: Int) {
self.data = data
next = nil
}
func appendToLast(data: Int) {
if (next != nil) {
next?.appendToLast(data: data)
} else {
next = Node(data: data)
}
}
}
//Function that return the reversed Linked List
func reverseLinkedList(node: Node?) -> Node? {
guard node != nil else { return nil }
var tail: Node?
var headNode = node
while let head = headNode {
let tailRef = head.next
head.next = tail
tail = head
headNode = tailRef
}
return tail
}
//Input all the data which we have in the linkedlist and output of that inside the print function.
let ll = Node(data: 3)
ll.appendToLast(data: 4)
ll.appendToLast(data: 4)
ll.appendToLast(data: 5)
let reversedLL = reverseLinkedList(node: ll)
print(reversedLL?.description ?? "No Data")

Swift 3 delete nodes from singly linked list

I am trying to remove all elements from a linked list of integers that have value val. Is it necessary to set the removed nodes to nil to free memory?
func removeElements(_ head: Node?, _ val: Int) -> Node? {
var first = head
var current = head
var prev: Node?
while current != nil {
if current?.val != val {
prev = current
} else if current?.val == first?.val {
var oldFirst = first
first = current?.next
oldFirst = nil // is this line necessary?
} else {
prev?.next = current?.next // do I need to set current to nil?
}
current = current?.next
}
return first
}
oldFirst = nil only sets the variable in your current scope to nil.
Again, current is a variable in your local scope, it gets already dereferenced and thus cleaned up once you leave its scope.
If you have no strong references to an object anymore it is released by itself because Swift uses Automatic Reference Counting (ARC: https://en.wikipedia.org/wiki/Automatic_Reference_Counting)
I am not sure why you have the 2nd case in your code. I guess it checks the case where the current node has value val but you compare to first.val instead of val
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
guard head != nil else {
return nil
}
let preDummy = ListNode(val: 0), postDummy = ListNode(val: 0)
var pre = preDummy, node = head
while node != nil {
if node!.val == val {
postDummy.next = node?.next
node!.next = nil
} else {
pre.next = node
pre = node!
}
node = node!.next
}
pre.next = postDummy.next
return preDummy.next
}

Binary tree implementation using Swift enum

I'm doing some experiments with Swift enums to become more familiarized with them and have implemented a rudimentary binary tree. It works when adding up to three items, but adding more beyond that doesn't change it and I couldn't see why it wasn't working.
Here's the code:
protocol TreeProtocol {
mutating func insert(value: Int)
func walk()
}
enum Tree:TreeProtocol {
case Empty
case Leaf(Int)
case Node(Int, TreeProtocol?, TreeProtocol?)
init(){
self = .Empty;
}
init(value: Int) {
self = .Leaf(value)
}
init(value: Int, left:TreeProtocol?, right:TreeProtocol?){
self = .Node(value, left, right);
}
mutating func insert(value: Int) {
switch self {
case .Empty:
self = .Leaf(value)
case .Leaf(let currentNodeValue):
let newTree = Tree(value: value) // var here generates a warning
if value < currentNodeValue {
self = .Node(currentNodeValue, newTree, .None)
}
else {
self = .Node(currentNodeValue, .None, newTree)
}
case let .Node(currentNodeValue, leftNode, rightNode):
if (value < currentNodeValue) {
if leftNode == nil {
let newTree = Tree(value: value)
self = .Node(currentNodeValue, newTree, rightNode)
}
else {
var l = leftNode! // unable to call leftNode!.insert() directly
l.insert(value)
}
}
else {
if rightNode == nil {
let newTree = Tree(value: value)
self = .Node(currentNodeValue, leftNode, newTree)
}
else {
var r = rightNode!
r.insert(value)
}
}
}
}
func walk() {
switch self {
case .Empty:
print("Empty")
case .Leaf (let value):
print("\(value), ")
case .Node(let value, let leftNode, let rightNode):
if leftNode != nil {
leftNode!.walk()
}
print("\(value) ")
if (rightNode != nil) {
rightNode!.walk()
}
}
}
}
And if I run the following tests:
var tree = Tree();
tree.walk()
tree.insert(100)
tree.walk()
tree.insert(50)
tree.walk()
tree.insert(150)
tree.walk()
tree.insert(25)
tree.walk()
The output is:
Empty
100
50,
100
50,
100,
150
50,
100,
150
The 25 value is not getting added to the tree
(This code is a bit inelegant, its just the first iteration, there's several ugly parts in there that could be improved and beautified. Waiting for recursive enum functionality to be added to the Xcode beta).
Because you're mutating the internal nodes and that is actually creating a copy of them. That copy is never inserted into the tree, it's just thrown away after being modified. If after inserting into l and r you reinsert those nodes (with self = .Node(currentNodeValue, l, rightNode) and self = .Node(currentNodeValue, leftNode, r) respectively) then the tree as a whole will get updated. It's a by-value / by-reference issue.
I know you already have an answer, but I really like your implementation and thought I'd provide the code for implementing #Wain's solution and also streamline some of the nested if-else logic.
It involves a slight modification for the protocol, so that insert returns a value:
protocol TreeProtocol {
mutating func insert(value: Int) -> TreeProtocol
func walk()
}
And then the insert function can be rewritten like this:
mutating func insert(value: Int) -> TreeProtocol {
switch self {
case .Empty:
self = .Leaf(value)
case .Leaf(let currentNodeValue):
let newTree = Tree(value: value)
self = value < currentNodeValue
? .Node(currentNodeValue, newTree, .None)
: .Node(currentNodeValue, .None, newTree)
case var .Node(currentNodeValue, leftNode, rightNode):
self = value < currentNodeValue
? .Node(currentNodeValue, leftNode?.insert(value) ?? Tree(value: value), rightNode)
: .Node(currentNodeValue, leftNode, rightNode?.insert(value) ?? Tree(value: value))
}
return self
}