root1
and root2
, return a list containing all the integers from both trees sorted in ascending order.[0, 5000]
.-10^5 <= Node.val <= 10^5
/**
* 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} root1
* @param {TreeNode} root2
* @return {number[]}
*/
var getAllElements = function(root1, root2) {
const result = [];
const dfs = (node1, node2) => {
if (!node1 && !node2) {
return;
}
if (node1) {
result.push(node1.val);
if (node1.left) {
dfs(node1.left);
}
if (node1.right) {
dfs(node1.right);
}
}
if (node2) {
result.push(node2.val);
if (node2.left) {
dfs(node2.left);
}
if (node2.right) {
dfs(node2.right);
}
}
};
dfs(root1, root2);
return result.sort((a,b) => a - b);
}
You are given an array of strings products
and a string searchWord
.
Design a system that suggests at most three product names from products
after each character of searchWord
is typed. Suggested products should have common prefix with searchWord
. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord
is typed.
Example 1:
Example 2:
1 <= products.length <= 1000
1 <= products[i].length <= 3000
1 <= sum(products[i].length) <= 2 * 10^4
products
are unique.products[i]
consists of lowercase English letters.1 <= searchWord.length <= 1000
searchWord
consists of lowercase English letters./**
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
var suggestedProducts = function(products, searchWord) {
const result = [];
products.sort();
for (let i = 1; i <= searchWord.length; i++) {
const prefix = searchWord.substring(0,i);
const commonPrefixProducts = [];
for (let j = 0; j < products.length; j++) {
if (commonPrefixProducts.length >= 3) {
break;
}
const product = products[j];
if (product.startsWith(prefix)) {
commonPrefixProducts.push(product);
}
}
result.push(commonPrefixProducts);
}
return result;
};
root
of a binary tree, invert the tree, and return its root.[0, 100]
.-100 <= Node.val <= 100
/**
* 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 {TreeNode}
*/
var invertTree = function(root) {
const queue = [root];
while (queue.length) {
const node = queue.shift();
if (node) {
const temp = node.left;
node.left = node.right;
node.right = temp;
queue.push(node.left, node.right);
}
}
return root;
};