Created
August 23, 2013 02:50
-
-
Save hbakhtiyor/6315080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var count_bottom_leaves = function(binary_tree) { | |
return helper(binary_tree, get_depth_leaf(binary_tree, 0), 0) | |
} | |
var helper = function(binary_tree, bound_depth, depth) { | |
if(binary_tree == false) { return 0 } | |
var left_node = get(binary_tree, 1) | |
var right_node = get(binary_tree, 2) | |
var left_cbl = 0 | |
var right_cbl = 0 | |
if(left_node == false && right_node == false) { | |
if(bound_depth == depth + 1) { return 1 } | |
else { return 0 } | |
} | |
else { | |
left_cbl = helper(left_node, bound_depth, depth + 1) | |
right_cbl = helper(right_node, bound_depth, depth + 1) | |
return left_cbl + right_cbl | |
} | |
} | |
var get_depth_leaf = function(binary_tree, depth) { | |
if(binary_tree == false) { return depth } | |
var left_node = get(binary_tree, 1) | |
var right_node = get(binary_tree, 2) | |
var left_depth = 0 | |
var right_depth = 0 | |
left_depth = get_depth_leaf(left_node, depth + 1) | |
right_depth = get_depth_leaf(right_node, depth + 1) | |
if(left_depth > right_depth) { return left_depth } | |
else { return right_depth } | |
} | |
print count_bottom_leaves(array(2, array(5, false, array(7, false, false)), array(9, false, false))) // => 1 | |
print count_bottom_leaves(array(2, array(5, false, array(7, false, false)), array(9, false, array(11, false, false)))) // => 2 | |
print count_bottom_leaves(array(2, array(5, array(6, false, false), array(7, false, false)), array(9, false, array(11, false, false)))) // => 3 | |
print count_bottom_leaves(array(2, array(5, array(6, false, false), array(7, false, false)), array(9, array(10, false, false), array(11, false, false)))) // => 4 | |
print count_bottom_leaves(array(2, array(5, array(6, false, false), array(7, false, false)), array(9, false, false))) // => 2 | |
print count_bottom_leaves(array(2, array(5, array(6, false, array(20, false, false)), array(7, false, false)), array(9, array(10, false, false), array(11, false, false)))) // => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment