半夜刷几道树和图的专题,其实都有做过,不过时间效率上优化了很多。
专题链接:探索中级算法——树与图
岛屿数量
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
Code
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
if(grid.length==0) return 0;
let row=grid.length,col=grid[0].length,res=0;
for(let i=0;i<grid.length;i++){
for(let j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
search(i,j);
res++;
}else{
continue;
}
}
}
function search(r,c){
if(r<0||r>=row||c<0||c>=col||grid[r][c]==0||grid[r][c]==2){
return;
}else if(grid[r][c]==1){
grid[r][c]=2;
search(r+1,c);
search(r,c+1);
search(r-1,c);
search(r,c-1);
return;
}
};
return res;
};
中序遍历二叉树
给定一个二叉树,返回它的中序遍历。使用迭代算法,不使用递归算法。
Code
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
//迭代法(在一个栈里面递归拆出子树)
var inorderTraversal = function(root) {
if(!root) return [];
let queue=[root];
let res=[];
while(queue.length!=0){
let node=queue.pop();
console.log(node);
if(node.val==undefined) res.push(node);
else{
if(node.right) queue.push(node.right);
queue.push(node.val);
if(node.left) queue.push(node.left);
}
}
return res;
};
//迭代法(两个栈)
var inorderTraversal = function(root) {
if(!root) return [];
let stack=[];
let res=[];
let cur=root;
while(cur||stack.length){
while(cur){
stack.push(cur);
cur=cur.left;
}
cur=stack.pop();
res.push(cur.val);
cur=cur.right;
}
return res;
};
二叉树的锯齿形层次遍历
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
Code
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
if(!root) return [];
let width=0;
let res=[];
let stack=[root];
while(stack.length){
let temp=[];
let newStack=[];
if(width&1){
while(stack.length){
let node=stack.pop();
temp.push(node.val);
if(node.right) newStack.push(node.right);
if(node.left) newStack.push(node.left);
}
}else{
while(stack.length){
let node=stack.pop();
temp.push(node.val);
if(node.left) newStack.push(node.left);
if(node.right) newStack.push(node.right);
}
}
width++;
stack=newStack;
res.push(temp);
}
return res;
};