Binary Tree Preorder Traversal
var preorderTraversal = function(root) {
if (!root) return []
const stack = [root]
const result = []
while (stack.length !== 0) {
const node = stack.pop()
result.push(node.val)
if (node.right) stack.push(node.right)
if (node.left) stack.push(node.left)
}
return result
}
Binary Tree Postorder Traversal
var postorderTraversal = function(root) {
if (!root) return []
const stack = [root]
const result = []
while (stack.length !== 0) {
const node = stack.pop()
if (node.left) stack.push(node.left)
if (node.right) stack.push(node.right)
result.unshift(node.val)
}
return result
}
Binary Tree Inorder Traversal
var inorderTraversal = function(root) {
if (!root) return []
const stack = []
const result = []
let current = root
while (stack.length !== 0 || current) {
if (current) {
stack.push(current)
current = current.left
} else {
const node = stack.pop()
result.push(node.val)
current = node.right
}
}
return result
}
Smallest Integer Divisible by K
var smallestRepunitDivByK = function(k) {
if(k % 2 === 0 && k % 5 === 0) return -1
let temp = 0
for(var i = 1; i <= k; i++){
temp = (temp * 10 + 1) % k
if(temp === 0) return i
}
return -1
}
更快的寫法:
var smallestRepunitDivByK = function(k) {
if(k % 2 === 0 && k % 5 === 0) return -1
let temp = 0
const arr = new Set ()
for(var i = 1; i <= k; i++){
temp = (temp * 10 + 1) % k
if(temp === 0) return i
if (arr.has(temp)) return -1
arr.add(temp)
}
return -1
}