|
| 1 | +/** |
| 2 | + * 919. Complete Binary Tree Inserter |
| 3 | + * https://leetcode.com/problems/complete-binary-tree-inserter/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A complete binary tree is a binary tree in which every level, except possibly the last, |
| 7 | + * is completely filled, and all nodes are as far left as possible. |
| 8 | + * |
| 9 | + * Design an algorithm to insert a new node to a complete binary tree keeping it complete |
| 10 | + * after the insertion. |
| 11 | + * |
| 12 | + * Implement the CBTInserter class: |
| 13 | + * - CBTInserter(TreeNode root) Initializes the data structure with the root of the complete |
| 14 | + * binary tree. |
| 15 | + * - int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that |
| 16 | + * the tree remains complete, and returns the value of the parent of the inserted TreeNode. |
| 17 | + * - TreeNode get_root() Returns the root node of the tree. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * Definition for a binary tree node. |
| 22 | + * function TreeNode(val, left, right) { |
| 23 | + * this.val = (val===undefined ? 0 : val) |
| 24 | + * this.left = (left===undefined ? null : left) |
| 25 | + * this.right = (right===undefined ? null : right) |
| 26 | + * } |
| 27 | + */ |
| 28 | +/** |
| 29 | + * @param {TreeNode} root |
| 30 | + */ |
| 31 | +var CBTInserter = function(root) { |
| 32 | + this.root = root; |
| 33 | + this.deque = []; |
| 34 | + |
| 35 | + const queue = [root]; |
| 36 | + while (queue.length) { |
| 37 | + const node = queue.shift(); |
| 38 | + if (!node.left || !node.right) this.deque.push(node); |
| 39 | + if (node.left) queue.push(node.left); |
| 40 | + if (node.right) queue.push(node.right); |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +/** |
| 45 | + * @param {number} val |
| 46 | + * @return {number} |
| 47 | + */ |
| 48 | +CBTInserter.prototype.insert = function(val) { |
| 49 | + const node = new TreeNode(val); |
| 50 | + const parent = this.deque[0]; |
| 51 | + if (!parent.left) { |
| 52 | + parent.left = node; |
| 53 | + } else { |
| 54 | + parent.right = node; |
| 55 | + this.deque.shift(); |
| 56 | + } |
| 57 | + this.deque.push(node); |
| 58 | + return parent.val; |
| 59 | +}; |
| 60 | + |
| 61 | +/** |
| 62 | + * @return {TreeNode} |
| 63 | + */ |
| 64 | +CBTInserter.prototype.get_root = function() { |
| 65 | + return this.root; |
| 66 | +}; |
0 commit comments