Created
June 18, 2024 14:31
-
-
Save carefree-ladka/f141d0efcefb0260f380daea7cdab425 to your computer and use it in GitHub Desktop.
Morris Traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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