|
| 1 | +/** |
| 2 | + * 998. Maximum Binary Tree II |
| 3 | + * https://leetcode.com/problems/maximum-binary-tree-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A maximum tree is a tree where every node has a value greater than any other value |
| 7 | + * in its subtree. |
| 8 | + * |
| 9 | + * You are given the root of a maximum binary tree and an integer val. |
| 10 | + * |
| 11 | + * Just as in the previous problem, the given tree was constructed from a list a |
| 12 | + * (root = Construct(a)) recursively with the following Construct(a) routine: |
| 13 | + * - If a is empty, return null. |
| 14 | + * - Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i]. |
| 15 | + * - The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]). |
| 16 | + * - The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]). |
| 17 | + * - Return root. |
| 18 | + * |
| 19 | + * Note that we were not given a directly, only a root node root = Construct(a). |
| 20 | + * |
| 21 | + * Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has |
| 22 | + * unique values. |
| 23 | + * |
| 24 | + * Return Construct(b). |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * Definition for a binary tree node. |
| 29 | + * function TreeNode(val, left, right) { |
| 30 | + * this.val = (val===undefined ? 0 : val) |
| 31 | + * this.left = (left===undefined ? null : left) |
| 32 | + * this.right = (right===undefined ? null : right) |
| 33 | + * } |
| 34 | + */ |
| 35 | +/** |
| 36 | + * @param {TreeNode} root |
| 37 | + * @param {number} val |
| 38 | + * @return {TreeNode} |
| 39 | + */ |
| 40 | +var insertIntoMaxTree = function(root, val) { |
| 41 | + if (!root || val > root.val) { |
| 42 | + const newRoot = createNode(val); |
| 43 | + newRoot.left = root; |
| 44 | + return newRoot; |
| 45 | + } |
| 46 | + |
| 47 | + root.right = insertIntoMaxTree(root.right, val); |
| 48 | + return root; |
| 49 | + |
| 50 | + function createNode(value) { |
| 51 | + return new TreeNode(value); |
| 52 | + } |
| 53 | +}; |
0 commit comments