原理
使用dfs
JS实现
力扣 257. 二叉树的所有路径
递归的过程本身就伴随着回溯,因为递归一方面是递,一方面是归,归的时候就会产生回溯,这道题我自己写的时候,在归的过程中,手动将保存路径的数组弹出刚添加的元素,但网上看一些版本,是没有这个过程的,这是为什么?回想起自己之前学的递归的原理–递归,瞬间明白
首先是自己写的版本
var binaryTreePaths = function (root) {
// 保存结果(多条路径组成)
let result = []
// 保存路径
let path = []
const dfs = function (root) {
// 最小子问题
if (root === null) return
// 递的过程
path.push(root.val)
if (root.left === null && root.right === null) {
result.push(path.join('->'))
}
dfs(root.left)
dfs(root.right)
// 归的过程
path.pop()
}
dfs(root)
return result
}
或者这样写也是一样
var binaryTreePaths = function(root) {
// 保存结果(多条路径组成)
let result = []
const dfs = function(root, path) {
// 最小子问题
if(root === null) return
// 递的过程
path.push(root.val)
if(root.left === null && root.right === null) {
result.push(path.join('->'))
}
dfs(root.left, path)
dfs(root.right, path)
// 归的过程
path.pop()
}
dfs(root, [])
return result
};
网上的版本
var binaryTreePaths = function(root) {
//递归遍历+递归三部曲
let res = [];
//1. 确定递归函数 函数参数
const getPath = function(node,curPath) {
//2. 确定终止条件,到叶子节点就终止
if(node.left === null && node.right === null) {
curPath += node.val;
res.push(curPath);
return;
}
//3. 确定单层递归逻辑
curPath += node.val + '->';
node.left && getPath(node.left, curPath);
node.right && getPath(node.right, curPath);
}
getPath(root, '');
return res;
};
仔细看我在内部函数中传入的是数组[],而他(网上版本)传入的是字符串,问题就在这里!!!!
数组是引用数据类型,传入的是地址,也就是说递归函数调用了多次,每次处理的path都是一个值;
而对于简单数据类型,递归函数调用了多次,每次处理的path却是不一样的(path只存活在每一个块级作用域中);
这时有同学就会说字符串在JS中不是引用数据类型嘛,这里要注意利用字面值或者string()函数创建的字符串都是简单数据类型,只有用new String()创建的才是引用数据类型