The question asks: Given the root of a binary tree, return the inorder traversal of its nodes' values. With an example input and out being:
Input: root = [1,null,2,3]
Output: [1,3,2]
I understand the recursive parts of this problem, but, how is it that by passing in the root into the helper function, a binary tree is created? Also, the 'node' in the path() function is an array, how is there then a node.left and node.right if it's an array and not an individual node? As we don't explicitly use the TreeNode(val,...) function, is there some magic going on in the background?
I do know that in array form, the formula for the node.right (2n+2) and node.left (2n+1) where n is the index of the element. However, we don't pass in an index or an individual element to which we can apply the formula, we pass in the entire array.
An explanation would be greatly appreciated.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
let result = []
const path = (node) => {
if (!node) return
if (node.left) path(node.left)
result.push(node.val)
if (node.right) path(node.right)
}
path(root)
return result
};
