Untitled
unknown
plain_text
2 months ago
2.2 kB
4
Indexable
1. Path Sum Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. function TreeNode(val, left, right) { this.val = (val===undefined ? 0 : val) this.left = (left===undefined ? null : left) this.right = (right===undefined ? null : right) } Solution: var hasPathSum = function(root, targetSum) { let sum = 0 return dfs(root, sum, targetSum) }; function dfs(root, sum, targetSum) { if (!root) { return false } sum += root.val if(root.left == undefined && root.right == underfined) { return sum == targetSum } return dfs(root.left, sum, tagetSum) || dfs(root.right, sum, tagetSum) } 2. Removing starts from a string You are given a string s, which contains stars *. In one operation, you can: - Choose a star in s. - Remove the closest non-star character to its left, as well as remove the star itself. - Return the string after all stars have been removed. The input will be generated such that the operation is always possible. Example Input: s = "leet**cod*e" Output: "lecoe" var removeStars = function(s) { let stack = [] for(let i = 0; i < s.length; i++) { if(!s[i] == '*') { stack.push(s[i]) } else { stack.pop(); } } return stack.join("") }; 3. Deepest leaves sum Given the root of a binary tree, return the sum of values of its deepest leaves. var deepestLeavesSum = function(root) { if(!root) { return; } let queue = [root] let sum = 0; while(queue.length > 0) { let size = queue.length; sum = 0; for(let i = 0; i < size; i++) { let curr = queue.shift(); sum += curr.val if(curr.left) { queue.push(curr.left) } if(curr.right) { queue.push(curr.right) } } } return sum }; It can be shown that the resulting string will always be unique.
Editor is loading...
Leave a Comment