diff --git a/Data-Structures/Tree/PreOrder.js b/Data-Structures/Tree/PreOrder.js new file mode 100644 index 0000000000..516431781f --- /dev/null +++ b/Data-Structures/Tree/PreOrder.js @@ -0,0 +1,10 @@ +function preOrder (root) { + if (root === null) return [] + + const left = preOrder(root.left) + const right = preOrder(root.right) + + return [root.value, ...left, ...right] +} + +export { preOrder } diff --git a/Data-Structures/Tree/test/PreOrder.test.js b/Data-Structures/Tree/test/PreOrder.test.js new file mode 100644 index 0000000000..1e24e7880c --- /dev/null +++ b/Data-Structures/Tree/test/PreOrder.test.js @@ -0,0 +1,92 @@ +import { preOrder } from '../PreOrder' + +describe('preOrder function', () => { + test('should return an empty array for an empty tree', () => { + const tree = null + expect(preOrder(tree)).toEqual([]) + }) + + test('should return an array with the root value for a tree with only one node', () => { + const tree = { + value: 5, + left: null, + right: null + } + expect(preOrder(tree)).toEqual([5]) + }) + + test('should return the correct array for a tree with multiple nodes', () => { + const tree = { + value: 5, + left: { + value: 3, + left: { + value: 2, + left: null, + right: null + }, + right: { + value: 4, + left: null, + right: null + } + }, + right: { + value: 7, + left: { + value: 6, + left: null, + right: null + }, + right: { + value: 8, + left: null, + right: null + } + } + } + expect(preOrder(tree)).toEqual([5, 3, 2, 4, 7, 6, 8]) + }) + + test('should return the correct array for a tree with a single branch to the left', () => { + const tree = { + value: 5, + left: { + value: 4, + left: { + value: 3, + left: { + value: 2, + left: null, + right: null + }, + right: null + }, + right: null + }, + right: null + } + expect(preOrder(tree)).toEqual([5, 4, 3, 2]) + }) + + test('should return the correct array for a tree with a single branch to the right', () => { + const tree = { + value: 5, + left: null, + right: { + value: 6, + left: null, + right: { + value: 7, + left: null, + right: { + value: 8, + left: null, + right: null + } + } + } + } + expect(preOrder(tree)).toEqual([5, 6, 7, 8]) + }) +}) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy