Created
August 27, 2020 18:31
-
-
Save greathmaster/d07be4829cd76e9500424f67346a3f19 to your computer and use it in GitHub Desktop.
Iterative solution for Leetcode Problem 114
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
//Iterative solution for Leetcode Problem 114. | |
//Currently having out of memory issues on Leetcode, but runs flawlessly on local Node setup | |
var flatten = function(root) { | |
if(root === null) return null; | |
const DOWN = 1; //represents performing a recursive function call | |
const UP = 2; //represents returning from a recursive function call | |
let stack = []; | |
let traversalState = DOWN; | |
let tail = null; | |
stack.push(root) | |
while(stack.length > 0) { | |
let node = stack[stack.length - 1]; | |
//we found a leaf node | |
if(node.left === null && node.right === null) { | |
traversalState = UP; //effectively we are "returning" after finding the leftmost node | |
tail = stack.pop(); | |
continue; | |
} | |
//keep traversing down the tree until we find a leaf node | |
if(traversalState == DOWN) { | |
if(node.left) { | |
stack.push(node.left) | |
} else if(node.right) { | |
stack.push(node.right) | |
} | |
} | |
//we have "returned" from the recursive call. Time to re-wire the nodes | |
if(traversalState === UP) { | |
if(tail) { | |
let node2 = stack.pop() | |
tail.right = node2.right; | |
node2.right = node2.left; | |
node2.left = null; | |
if(tail.right) { | |
stack.push(tail.right) | |
traversalState = DOWN; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment