CoDEVIANT #24 — Apples Falling from the Binary Tree

Mmmm…sweet, candy red apples…

“If I go down a pace to either the left or right side, I know I’m going to find one apple if there’s a harvest going on there. I also know that if I go further down to either the left or right side, I’m going to find two apples. Now if those trees that had two apples have a path leading to another apple tree further down the road, I know I’m going to see a tree that will give me three apples!”

You can visit any apple-tree (node), as often as you like, but you can’t pick up an apple that is already retrieved.
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function nodeDepths(root) {
let depthCount = 0
return helper(root, depthCount)
}
function helper(node, counter) {
if(!node) {
return 0
}
let numbah = counter + helper(node.right, counter + 1) + helper(node.left, counter + 1)
return numbah
}
class BinaryTree {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
function nodeDepths(root) {
let depthCount = 0
return helper(root, depthCount)
}
function helper(node, counter) {
if(!node) {
return 0
}
let numbah = counter + helper(node.right, counter + 1) + helper(node.left, counter + 1)
return numbah
}
Yay recursion!
How’d you like dem apples?

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store