{"ScriptPreparationCode":"class TreeNode {\r\n constructor(val, left, right) {\r\n this.val = val === undefined ? 0 : val;\r\n this.left = left === undefined ? null : left;\r\n this.right = right === undefined ? null : right;\r\n }\r\n}\r\n\r\nfunction goodNodes(root) {\r\n if (!root) return 0;\r\n\r\n const stack = [root];\r\n const max = [root.val];\r\n let count = 1;\r\n\r\n while (stack.length \u003E 0) {\r\n const curr = stack.pop();\r\n const currMax = max.pop();\r\n if (curr.left) {\r\n const left = curr.left;\r\n if (left.val \u003E= currMax) {\r\n count \u002B= 1;\r\n max.unshift(left.val);\r\n } else {\r\n max.unshift(currMax);\r\n }\r\n stack.unshift(left);\r\n }\r\n if (curr.right) {\r\n const right = curr.right;\r\n if (right.val \u003E= currMax) {\r\n count \u002B= 1;\r\n max.unshift(right.val);\r\n } else {\r\n max.unshift(currMax);\r\n }\r\n stack.unshift(right);\r\n }\r\n }\r\n\r\n return count;\r\n}\r\n \r\nfunction buildTreeFromArray(arr) {\r\n if (!arr.length || arr[0] === null) return null;\r\n\r\n const nodes: (TreeNode | null)[] = arr.map((val) =\u003E\r\n val !== null ? new TreeNode(val) : null\r\n );\r\n\r\n for (let i = 0; i \u003C nodes.length; i\u002B\u002B) {\r\n if (nodes[i] !== null) {\r\n const leftIndex = 2 * i \u002B 1;\r\n const rightIndex = 2 * i \u002B 2;\r\n const curr = nodes[i] as TreeNode;\r\n\r\n if (leftIndex \u003C nodes.length) {\r\n curr.left = nodes[leftIndex];\r\n }\r\n\r\n if (rightIndex \u003C nodes.length) {\r\n curr.right = nodes[rightIndex];\r\n }\r\n }\r\n }\r\n\r\n return nodes[0];\r\n}","TestCases":[{"Name":"first","Code":"const input = [3, 1, 4, 3, null, 1, 5];\r\nconst tree = buildTreeFromArray(input);\r\ngoodNodes(tree)","IsDeferred":false},{"Name":"second","Code":"const input = [3,3,null,4,2];\r\nconst tree = buildTreeFromArray(input);\r\ngoodNodes(tree)","IsDeferred":false},{"Name":"third","Code":"const input = [1];\r\nconst tree = buildTreeFromArray(input);\r\ngoodNodes(tree)","IsDeferred":false},{"Name":"forth","Code":"const input = [3, 2, 5, 3, 4, 8, 1, 6, null, null, null, 7, null, 13, 9];\r\nconst tree = buildTreeFromArray(input);\r\ngoodNodes(tree)","IsDeferred":false}]}