From 2471a08c95816ee5c98072b3e829229049bebdda Mon Sep 17 00:00:00 2001 From: Tia Low Date: Thu, 8 Oct 2020 21:57:58 -0700 Subject: [PATCH 1/2] Function to determine if a linked list is a palindrome --- listPalindrome.js | 59 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 listPalindrome.js diff --git a/listPalindrome.js b/listPalindrome.js new file mode 100644 index 0000000..0af32bf --- /dev/null +++ b/listPalindrome.js @@ -0,0 +1,59 @@ +'use strict'; + +// Javascript implementation of a stand alone function that determines if a linked list is a palindrome +// function's signature is a linked list as a parameter and returns true if it's a palindrome, false if not +// relies on a linked list node implementation as written below + +class Node { + + constructor(value, next = null) { + this.value = value; + this.next = next; + } +} + + +class LinkedList { + + constructor() { + this.head = null; + } + + insert(value) { + this.head = new Node(value, this.head); + } + +} + +function determineListPalindrome(linkedList) { + + let arr =[]; + + let currentNode = linkedList.head; + + if(currentNode) { + arr.push(currentNode.value); + } + + while(currentNode.next) { + currentNode = currentNode.next; + arr.push(currentNode.value); + } + + for(let i = 0; i < arr.length/2; i++) { + + if(arr[i] !== arr[arr.length - ( i + 1 ) ] ){ + + return false; + + } + + return true; + + } + + +} + + + From a3cc85971bace058290b377715d2461c77b5e5df Mon Sep 17 00:00:00 2001 From: Tia Low Date: Thu, 8 Oct 2020 22:29:53 -0700 Subject: [PATCH 2/2] JS function to determine how many leaves are in a binary tree --- leavesBinaryTree.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 leavesBinaryTree.js diff --git a/leavesBinaryTree.js b/leavesBinaryTree.js new file mode 100644 index 0000000..7ca2b90 --- /dev/null +++ b/leavesBinaryTree.js @@ -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; + +}