You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode}l1 * @param {ListNode}l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { let dummy=new ListNode(0), cur=dummy, carry=0; while(l1||l2) { let val1=l1?l1.val:0, val2=l2?l2.val:0; let val=val1+val2+carry; let node=new ListNode(val%10); carry=Math.floor(val/10); cur.next=node; cur=node; if(l1) l1=l1.next; if(l2) l2=l2.next; } if(carry) { let node=new ListNode(carry); cur.next=node; cur=node; } cur.next=null; return dummy.next; };
15. 3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
1 2 3
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
1 2 3 4 5 6 7 8
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode}head * @return {ListNode} */ var swapPairs = function(head) { let dummy={val:0,next:head}, cur=dummy; while(cur.next&&cur.next.next) { let node1=cur.next, node2=cur.next.next; node1.next=node2.next; node2.next=node1; cur.next=node2; cur=cur.next.next; } return dummy.next; };
25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
functionreverseK(a,b) { //翻转[a,b)的链表 let prev=null, cur=a; while(cur!==b) { let next=cur.next; cur.next=prev; prev=cur; cur=next; } return prev; }
39. Combination Sum
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
1 2 3 4 5 6
Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,2,3] ]
Example 2:
1 2 3 4 5 6 7
Input: candidates = [2,3,5], target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ]
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
1 2 3 4 5 6 7 8
Input: candidates = [10,1,2,7,6,1,5], target = 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
1 2 3 4 5 6
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
1 2 3 4 5
Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
1 2 3 4 5 6 7
Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode}root * @return {number[][]} */ var levelOrder = function(root) { if(!root) return []; let res=[], queue=[root]; while(queue.length) { let temp=[], len=queue.length; //保证了这一循环都是处于一层的 for(let i=0;i<len;i++) { temp.push(queue[i].val); if(queue[i].left) queue.push(queue[i].left); if(queue[i].right) queue.push(queue[i].right); } res.push(temp); queue.splice(0,len); } return res; };
103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree [3,9,20,null,null,15,7],
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode}root * @return {number[][]} */ var levelOrderBottom = function(root) { if(!root) return []; let res=[], queue=[root]; while(queue.length){ let temp=[], len=queue.length; for(let i=0;i<len;i++){ temp.push(queue[i].val); if(queue[i].left) queue.push(queue[i].left); if(queue[i].right) queue.push(queue[i].right); } res.unshift(temp); queue.splice(0,len); } return res; };
109. Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
1 2 3 4 5 6 7 8 9
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
1 2 3
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
1 2 3
Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
1 2
Input: k = 3, n = 7 Output: [[1,2,4]]
Example 2:
1 2
Input: k = 3, n = 9 Output: [[1,2,6], [1,3,5], [2,3,4]]
235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
Example:
1 2 3 4 5 6 7 8
Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2]
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode}root * @return {number} */ var findBottomLeftValue = function(root) { let queue=[root], node; while(queue.length) { //层序遍历的时候可以从右向左放 这样最后一个pop出来的就是最后一行最左边的元素 node=queue.pop(); if(node.right) queue.unshift(node.right); if(node.left) queue.unshift(node.left); } return node.val; };
518. Coin Change 2
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Example 1:
1 2 3 4 5 6 7
Input: amount = 5, coins = [1, 2, 5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1
Example 2:
1 2 3
Input: amount = 3, coins = [2] Output: 0 Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
1 2
Input: amount = 10, coins = [10] Output: 1
code
1 2
530. Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
Input:
1 \ 3 / 2
Output: 1
Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode}root * @return {number} */ var getMinimumDifference = function(root) { let node=root, stack=[], prenode=null, min=Number.MAX_VALUE; while(node||stack.length) { while(node) { stack.push(node); node=node.left; } let now=stack.pop(); if(prenode) min=Math.min(Math.abs(now.val-prenode.val),min); prenode=now node=now.right; } return min; };
538. Convert BST to Greater Tree
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
1 2 3 4 5 6 7 8 9
Input: The root of a Binary Search Tree like this: 5 / \ 2 13
Output: The root of a Greater Tree like this: 18 / \ 20 13
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode}root * @return {TreeNode} */ var convertBST = function(root) {//递归的话 就按照右-根-左累加 let sum=0, cur=root, stack=[]; while(cur||stack.length) { while(cur) { stack.push(cur); cur=cur.right; } let node=stack.pop(); node.val+=sum; sum=node.val; cur=node.left; } return root; };
572. Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1: Given tree s:
1 2 3 4 5
3 / \ 4 5 / \ 1 2
Given tree t:
1 2 3
4 / \ 1 2
Return true, because t has the same structure and node values with a subtree of s.
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode}t1 * @param {TreeNode}t2 * @return {TreeNode} */ var mergeTrees = function(t1, t2) { if(!t1&&!t2) returnnull; if(!t1||!t2) return t1||t2; let root=new TreeNode(t1.val+t2.val); root.left=mergeTrees(t1.left,t2.left); root.right=mergeTrees(t1.right,t2.right); return root; };
637. Average of Levels in Binary Tree
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
1 2 3 4 5 6 7 8 9
Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
1 2 3 4 5 6 7 8 9
Input: 2 / \ 2 5 / \ 5 7
Output: 5 Explanation: The smallest value is 2, the second smallest value is 5.
Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list “parts”.
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode’s representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
Example 1:
1 2 3 4 5 6 7 8
Input: root = [1, 2, 3], k = 5 Output: [[1],[2],[3],[],[]] Explanation: The input and each element of the output are ListNodes, not arrays. For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null. The first element output[0] has output[0].val = 1, output[0].next = null. The last element output[4] is null, but it's string representation as a ListNode is [].
Example 2:
1 2 3 4 5
Input: root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3 Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] Explanation: The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Note:
The length of root will be in the range [0, 1000].
Each value of a node in the input will be an integer in the range [0, 999].
1008. Construct Binary Search Tree from Preorder Traversal
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {number[]}preorder * @return {TreeNode} */ var bstFromPreorder = function(preorder) { const inorder=preorder.slice().sort((a,b)=>a-b); let pLeft=0, pRight=preorder.length-1, iLeft=0, iRight=inorder.length-1; return buildTree(pLeft,pRight,iLeft,iRight) functionbuildTree(pLeft,pRight,iLeft,iRight) { if(pLeft>pRight||iLeft>iRight) returnnull; let i=iLeft; for(;i<=iRight;i++) { if(inorder[i]===preorder[pLeft]) break; } let node=new TreeNode(preorder[pLeft]); node.left=buildTree(pLeft+1,pLeft+i-iLeft,iLeft,i-1); node.right=buildTree(pLeft+1+i-iLeft,pRight,i+1,iRight); return node; } };
1038. Binary Search Tree to Greater Sum Tree
Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.