Skip to content

Instantly share code, notes, and snippets.

@BrianLitwin
Last active May 27, 2018 17:49
Show Gist options
  • Save BrianLitwin/132a24940d09bbee69a4a31325959eb5 to your computer and use it in GitHub Desktop.
Save BrianLitwin/132a24940d09bbee69a4a31325959eb5 to your computer and use it in GitHub Desktop.
func nodesAtEachDepth(from startNode: BinaryTreeNode) -> [[BinaryTreeNode]] {
var nodes = [[BinaryTreeNode]]()
return findDepths(depth: 0, node: startNode, nodes: &nodes)
}
func findDepths(depth: Int, node: BinaryTreeNode?, nodes: inout [[BinaryTreeNode]]) -> [[BinaryTreeNode]] {
guard let node = node else { return nodes }
var startingNewDepth = nodes.count <= depth
//1
if startingNewDepth {
nodes[depth] = [node]
} else {
nodes[depth].append(node)
}
//2
nodes = findDepths(depth: depth + 1, node: node.left, nodes: &nodes)
nodes = findDepths(depth: depth + 1, node: node.right, nodes: &nodes)
return nodes
}
1.
depth = 0
nodes.count = 0
startingNewDepth = true
nodes = [[node]]
find depths for left child
depth = 1
nodes.count = 1
startingNewDepth = true
nodes = [[node][node]]
lets say both left child's children are nil
find depths for right child
you've already visited this depth, so the array will contain at least one item
at array[depth], and thus the array.count will be > than the depth
depth = 1
nodes.count = 2
startingNewDepth = false
nodes = [[node][node]]
nodes[depth] = [node] eg nodes[1].append(newNode)
nodes = [[node][node, node]]
will then call finddepths on newNodes children, incrementing depth by 1
2.
explanation of the recursion
lets say the start node has two children: the left node is a leaf and the right child has two leaves
#1 you'll first add calls to the two children to the call stack
#2 then you'll execute the call to the left and right children, at depth 0 + 1
#3 then add the calls to the right nodes two children
#4 then add the calls to right and left nodes children
#1
call(L, depth: 1)
call(R, depth: 1)
#2
call(L, depth: 1)
call(L-L, depth: 2) //base case
call(L-R, depth: 2) // base case
call(R, depth: 1)
#3
call(L, depth: 1)
call(L-L, depth: 2) //base case
call(L-R, depth: 2) // base case
call(R, depth: 1)
call(R-L, depth: 2)
call(R-R, depth: 2)
#4
call(L, depth: 1)
call(L-L, depth: 2) // returns nil, base case
call(L-R, depth: 2) // returns nil, base case
call(R, depth: 1)
call(R-L, depth: 2)
call(R-L-L, depth: 3) // returns nil, base case
call(R-L-R, depth: 3) // returns nil, base case
call(R-R, depth: 2)
call(R-R-L, depth: 3) // returns nil, base case
call(R-R-R, depth: 3) // returns nil, base case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment