题目描述(leetcode传送门):
给定一个二叉树,求所有从根节点到叶子节点的路径。
结合二叉树的数据结构,容易联想到用递归的方式,先上代码:
var binaryTreePaths = function(root) {
if(root == null)
return []
if (root.left == null && root.right == null)
return [root.val.toString()]
//递归
let letChildPath = binaryTreePaths(root.left).map(item => root.val + '->' + item)
let rightChildPath = binaryTreePaths(root.right).map(item => root.val + '->' + item)
return letChildPath.concat(rightChildPath)
};
思路分析:
- 判断根节点是否为空
- 判断二叉树是否只有根节点(如果是,结合题干测试用例,返回值需要将根节点转为字符串类型)
- 递归遍历左子树及右子树
- 拼接左右子树遍历的结果
可以通过使用ES6的解构赋值语法,让代码更简洁:
var binaryTreePaths = function(root) {
if(root == null)
return []
if (root.left == null && root.right == null)
return [root.val.toString()]
return [...binaryTreePaths(root.left).map(item => root.val + '->' + item),
...binaryTreePaths(root.right).map(item => root.val + '->' + item)]
};