Last active
August 10, 2024 12:44
-
-
Save carefree-ladka/18dd437a674606230659782d56f569b2 to your computer and use it in GitHub Desktop.
BinaryTree recursive & iterative implementaion
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 TreeNode { | |
| constructor(val = 0, left = null, right = null) { | |
| this.val = val; | |
| this.left = left; | |
| this.right = right; | |
| } | |
| } | |
| const buildTree = (arr) => { | |
| const build = (index) => { | |
| if (index >= arr.length || !arr[index]) return null | |
| const node = new TreeNode(arr[index]) | |
| node.left = build(2 * index + 1) | |
| node.right = build(2 * index + 2) | |
| return node | |
| } | |
| return build(0) | |
| } | |
| console.log(buildTree([1, 2, 3, 4, 5, 6, 7])); | |
| //------------------------------------------------------------------------------- | |
| function buildBinaryTree(arr) { | |
| if (arr.length === 0) return null; | |
| const nodes = arr.map(val => val ? new TreeNode(val) : null); | |
| const n = nodes.length; | |
| for (let i = 0; i < n; i++) { | |
| if (nodes[i] !== null) { | |
| const leftIndex = 2 * i + 1; | |
| const rightIndex = 2 * i + 2; | |
| if (leftIndex < n) nodes[i].left = nodes[leftIndex]; | |
| if (rightIndex < n) nodes[i].right = nodes[rightIndex]; | |
| } | |
| } | |
| return nodes[0]; | |
| } | |
| /* | |
| 1 | |
| / \ | |
| 2 3 | |
| / \ / \ | |
| 4 5 6 7 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment