Created
June 5, 2018 22:21
-
-
Save TomaQ/5cdef5145c7108340e24507f87c31bf4 to your computer and use it in GitHub Desktop.
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
class Node { | |
constructor(value) { | |
this.value = value; | |
// own props for easier object shape recognition | |
this.left = null; | |
this.right = null; | |
} | |
} | |
const traverse = (root) => { | |
console.log(root.value); | |
if (root.left != null) { | |
traverse(root.left); | |
} | |
if(root.right != null) { | |
traverse(root.right); | |
} | |
}; | |
/** | |
* Runtime: O(n), where n is the number of nodes. | |
* Solution: Print the current node. After, recursively call on the left node which will then print the left node and repeat. | |
* Once you are at the end of the tree on the left it will go to the parent node (in the previous call) and go to the right node. | |
* Then it will go up the stack until it reaches the root node and traverse the right side, starting on the left. | |
* It's hard typing up the explanation...' | |
**/ | |
const first = new Node(1); | |
const second = new Node(2); | |
const third = new Node(3); | |
const fourth = new Node(4); | |
const fifth = new Node(5); | |
const sixth = new Node(6); | |
const seventh = new Node(7); | |
first.left = second; | |
first.right = fifth; | |
second.left = third; | |
second.right = fourth; | |
fifth.left = sixth; | |
fifth.right = seventh; | |
traverse(first); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment