|
| 1 | +/* |
| 2 | + * Author: Surendra Kumar |
| 3 | + * DFS Algorithm implementation in JavaScript |
| 4 | + * DFS Algorithm for traversing or searching graph data structures. |
| 5 | +*/ |
| 6 | + |
| 7 | +function traverseDFS (root) { |
| 8 | + const stack = [root] |
| 9 | + const res = [] |
| 10 | + |
| 11 | + while (stack.length) { |
| 12 | + const curr = stack.pop() |
| 13 | + res.push(curr.key) |
| 14 | + |
| 15 | + if (curr.right) { |
| 16 | + stack.push(curr.right) |
| 17 | + } |
| 18 | + |
| 19 | + if (curr.left) { |
| 20 | + stack.push(curr.left) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return res.reverse() |
| 25 | +} |
| 26 | + |
| 27 | +function searchDFS (tree, value) { |
| 28 | + var stack = [] |
| 29 | + |
| 30 | + stack.push(tree[0]) |
| 31 | + |
| 32 | + while (stack.length !== 0) { |
| 33 | + for (let i = 0; i < stack.length; i++) { |
| 34 | + var node = stack.pop() |
| 35 | + |
| 36 | + if (node.value === value) { |
| 37 | + return node |
| 38 | + } |
| 39 | + if (node.right) { |
| 40 | + stack.push(tree[node.right]) |
| 41 | + } |
| 42 | + if (node.left) { |
| 43 | + stack.push(tree[node.left]) |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return null |
| 48 | +} |
| 49 | + |
| 50 | +var tree = [ |
| 51 | + { value: 6, left: 1, right: 2 }, |
| 52 | + { value: 5, left: 3, right: 4 }, |
| 53 | + { value: 7, left: null, right: 5 }, |
| 54 | + { value: 3, left: 6, right: null }, |
| 55 | + { value: 4, left: null, right: null }, |
| 56 | + { value: 9, left: 7, right: 8 }, |
| 57 | + { value: 2, left: 9, right: null }, |
| 58 | + { value: 8, left: null, right: null }, |
| 59 | + { value: 10, left: null, right: null }, |
| 60 | + { value: 1, left: null, right: null } |
| 61 | +] |
| 62 | + |
| 63 | +searchDFS(tree, 9) |
| 64 | +searchDFS(tree, 10) |
| 65 | + |
| 66 | +traverseDFS(6) |
| 67 | + |
| 68 | +// 6 |
| 69 | +// / \ |
| 70 | +// 5 7 |
| 71 | +// / \ \ |
| 72 | +// 3 4 9 |
| 73 | +// / / \ |
| 74 | +// 2 8 10 |
| 75 | +// / |
| 76 | +// 1 |
0 commit comments