Last active
August 12, 2024 12:40
-
-
Save kshirish/09beec32ab10ab7a9aa7d54378e4ce87 to your computer and use it in GitHub Desktop.
Binary Tree (BT)
This file contains hidden or 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
// Root | |
// | | |
// | | |
// 11 12 | |
// | | | |
// | | | |
// 13 14 15 16 | |
// | | |
// | | |
// 17 18 | |
class TreeNode { | |
constructor(value) { | |
this.value = value; | |
this.left = null; | |
this.right = null; | |
} | |
} | |
const rootNode = new TreeNode('Root'); | |
rootNode.left = new TreeNode(11); | |
rootNode.right = new TreeNode(12); | |
rootNode.left.left = new TreeNode(13); | |
rootNode.left.right = new TreeNode(14); | |
rootNode.right.left = new TreeNode(15); | |
rootNode.right.right = new TreeNode(16); | |
rootNode.left.left.left = new TreeNode(17); | |
rootNode.left.left.right = new TreeNode(18); | |
function dfs(rootNode) { | |
let stack = [rootNode] | |
let results = []; | |
while(true) { | |
const node = stack.pop(); | |
if(!node) { | |
break; | |
} | |
results.push(node.value); | |
if(node.right) { | |
stack.push(node.right) | |
} | |
if(node.left) { | |
stack.push(node.left) | |
} | |
} | |
return results; | |
} | |
dfs(rootNode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment