在树、图中找值
-
每个节点都要访问一次
-
对于节点的访问顺序不同,常见深度优先、广度(层级)优先两种。
-
BFS 广度优先,代码模板
function bfs(node){
if(!node) return
const stack = [node]
const res =[]
while(!stack.length ===0){
const val = stack.pop()
if(val) 是否访问过
for(let i;i<node.children;i++){
stack.push(node_children[i])
}
}
}
- DFS 深度优先,代码模板(递归写法、非递归写法)
// 递归写法
const visited = new Set()
const dfs = node => {
if (visited.has(node)) return
visited.add(node)
// 二叉树
dfs(node.left)
dfs(node.right)
//或者 for next_node in node.children()
}
- 二分查找模板
查找是计算机中最基本也是最有用的算法之一
function binarySearch(data, arr, start, end) {
if (start > end) {
return -1;
}
var mid = Math.floor((end + start) / 2);
if (data == arr[mid]) {
return mid;
} else if (data < arr[mid]) {
return binarySearch(data, arr, start, mid - 1);
} else {
return binarySearch(data, arr, mid + 1, end);
}
}
实战题目
• leetcode-cn.com/problems/bi…
二叉树的层序遍历
var levelOrder = function(root) {
const ret = []
if(!root){
return ret
}
const q = []
q.push(root)
while(q.length !== 0){
const currentLevelSize = q.length
ret.push([])
for(let i=1;i<=currentLevelSize;++i){
const node = q.shift()
ret[ret.length - 1].push(node.val)
if(node.left) q.push(node.left)
if(node.right) q.push(node.right)
}
}
return ret
};
• leetcode-cn.com/problems/mi…
• leetcode-cn.com/problems/ge…
• leetcode-cn.com/problems/fi…
课后作业
• leetcode-cn.com/problems/wo…
• leetcode-cn.com/problems/wo…
• leetcode-cn.com/problems/nu…
• leetcode-cn.com/problems/mi…
- 贪心算法 动态规划