递归算法主要有三个步骤:
- 找到递归出口,整个递归的终止条件
- 返回上一级的内容
- 本级递归该做什么
1、遍历二叉树,递归与非递归实现
递归实现:
function deepSearch1(root, target){
if(root == null) return false;
if(root.value == target) return true;
var left = deepSearch1(root.left, target);
var right = deepSearch1(root.right, target);
return left || right;
}
console.log(deepSearch1(a, 'a')) // true
非递归实现:
function deepSearch2(root, target){
var arr = [];
arr.push(root)
while(arr.length){
var root = arr.pop();
if(root.value == target) return true;
if(root.left) arr.push(root.left)
if(root.right) arr.push(root.right)
}
return false
}
console.log(deepSearch2(a, 'c')) //true
2、数组扁平化,对象扁平化?
数组扁平化:
var arr = [1, [2,3], [2,3,[4,5,6]]];
var newArr = [];
function fn(arr){
arr.map(item => {
if(Array.isArray(item)){
fn(item);
}else{
newArr = newArr.concat(item)
}
})
return newArr
}
console.log(fn(arr)) //[1, 2, 3, 2, 3, 4, 5, 6]
对象扁平化:
var newObj = {}
function fn(obj){
for(var prop in obj){
if(typeof obj[prop] == 'object'){
fn(obj[prop])
}else{
newObj[prop] = obj[prop]
}
}
return newObj
}
console.log(fn(obj))
3、链表反转
function turnBack(root){
if(root.next.next == null){
root.next.next = root;
return root.next;
}else{
var result = turnBack(root.next);
root.next.next = root;
root.next = null;
return result;
}
}
console.log(turnBack(a))