Skip to content

Commit

Permalink
solve inorder tree traversal by stack alternative
Browse files Browse the repository at this point in the history
  • Loading branch information
pallabez committed Sep 13, 2023
1 parent b23cd4a commit 67fb925
Show file tree
Hide file tree
Showing 3 changed files with 2,738 additions and 4,372 deletions.
22 changes: 21 additions & 1 deletion Binary Search Tree/inorder_tree_walk.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,27 @@ function inorderTreeWalkByStack(root) {
}
}

function inorderTreeWalkByStackAlternative(root) {
if (root == null) return;

let stack = [];
let curr = root;

while (curr != null || stack.length != 0) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}

curr = stack.pop();
console.log(curr.element);

curr = curr.right;
}
}

module.exports = {
inorderTreeWalkByRecursion,
inorderTreeWalkByStack
inorderTreeWalkByStack,
inorderTreeWalkByStackAlternative
}
25 changes: 24 additions & 1 deletion Binary Search Tree/inorder_tree_walk.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { inorderTreeWalkByRecursion, inorderTreeWalkByStack } = require('./inorder_tree_walk');
const { inorderTreeWalkByRecursion, inorderTreeWalkByStack, inorderTreeWalkByStackAlternative } = require('./inorder_tree_walk');
const { BinarySearchTree } = require('./BST');

describe('Inorder Tree Walk', () => {
Expand Down Expand Up @@ -47,4 +47,27 @@ describe('Inorder Tree Walk', () => {
expect(consoleLogSpy).toHaveBeenNthCalledWith(3, 3);
})
})

describe('By Stack alternative', () => {
it('should print null', () => {
inorderTreeWalkByStackAlternative(bst.root);
})

it('should print out element using console', () => {
bst.add(2);
bst.add(3);
bst.add(1);
bst.add(4);
bst.add(5);
bst.add(6);

inorderTreeWalkByStackAlternative(bst.root);
expect(consoleLogSpy).toHaveBeenNthCalledWith(1, 1);
expect(consoleLogSpy).toHaveBeenNthCalledWith(2, 2);
expect(consoleLogSpy).toHaveBeenNthCalledWith(3, 3);
expect(consoleLogSpy).toHaveBeenNthCalledWith(4, 4);
expect(consoleLogSpy).toHaveBeenNthCalledWith(5, 5);
expect(consoleLogSpy).toHaveBeenNthCalledWith(6, 6);
})
})
});
Loading

0 comments on commit 67fb925

Please sign in to comment.