-
Notifications
You must be signed in to change notification settings - Fork 138
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
JS function to determine how many leaves are in a binary tree
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
'use strict'; | ||
|
||
// JavaScript implementation of a function that finds the number of leaves in a binary tree | ||
// function's signature is a binary tree as a parameter, returns the number of leaves in the tree | ||
// relies on the assumption that the input is a binary tree with a root, and made up of nodes with left and right properties on them, as illustrated below | ||
// function uses preOrder depth traversal method | ||
|
||
class Node { | ||
|
||
constructor(value, left = null, right = null) { | ||
this.value = value; | ||
this.left = left; | ||
this.right = right; | ||
} | ||
|
||
} | ||
|
||
class BinaryTree { | ||
|
||
constructor( root = null) { | ||
this.root = root; | ||
} | ||
|
||
} | ||
|
||
function numLeavesInTree(binaryTree) { | ||
|
||
let numLeaves = 0; | ||
|
||
function _preOrderTraversal(root) { | ||
|
||
if(!root) { | ||
return; | ||
} | ||
|
||
numLeaves += 1; | ||
_preOrderTraversal(root.left); | ||
_preOrderTraversal(root.right); | ||
|
||
} | ||
|
||
_preOrderTraversal(binaryTree.root); | ||
return numLeaves; | ||
|
||
} |