Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created June 18, 2024 14:31
Show Gist options
  • Save carefree-ladka/f141d0efcefb0260f380daea7cdab425 to your computer and use it in GitHub Desktop.
Save carefree-ladka/f141d0efcefb0260f380daea7cdab425 to your computer and use it in GitHub Desktop.
Morris Traversal
const inorderTraversal=function(root){
let node = root;
const result=[]
while (node) {
if (!node.left) {
result.push(node.val);
node = node.right;
} else {
const predecessor = findPredecessor(node);
if (predecessor.right === node) {
//We have a cycle
predecessor.right = null; //Break the cycle
// console.log(node.val);
result.push(node.val);
node = node.right;
} else {
predecessor.right = node; //if visiting for the first time, create a cycle
node = node.left;
}
}
}
return result
}
function findPredecessor(root){
let node=root.left
while(node.right && node.right!==root){
node=node.right
}
return node
}
//Preorder
const preorderTraversal = function(root) {
let node = root;
const result = [];
while (node) {
if (!node.left) {
result.push(node.val); // Visit the node
node = node.right;
} else {
const predecessor = findPredecessor(node);
if (predecessor.right === node) {
// We have a cycle
predecessor.right = null; // Break the cycle
node = node.right;
} else {
result.push(node.val); // Visit the node
predecessor.right = node; // Create a cycle
node = node.left;
}
}
}
return result;
};
function findPredecessor(root) {
let node = root.left;
while (node.right && node.right !== root) {
node = node.right;
}
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment