leetcode 算法题057 (简单068) 二叉树的所有路径
- 题目介绍
给定一个二叉树,返回所有从根节点到叶子节点的路径。
- 说明
叶子节点是指没有子节点的节点。
- 示例
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
- 解法一
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
if(!root) {
return [];
}
const paths = [];
root.path = root.val.toString();
addTreePaths(paths, root);
return paths;
};
const addTreePaths = (paths, root) => {
let basePath = root.path;
if(root.left) {
root.left.path = basePath + '->' + root.left.val;
addTreePaths(paths, root.left);
}
if(root.right) {
root.right.path = basePath + '->' + root.right.val;
addTreePaths(paths, root.right);
}
if(!(root.left || root.right)) {
paths.push(root.path);
}
}
执行用时 : 72 ms, 在所有 JavaScript 提交中击败了96.43%的用户
内存消耗 : 34.3 MB, 在所有 JavaScript 提交中击败了58.00%的用户
- 解法二
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
if(!root) {
return [];
}
let paths = [], temp = [root];
root.path = root.val.toString();
while(temp.length > 0) {
let i = 0; tArray = [];
while(i < temp.length) {
let node = temp[i++];
if(node.left) {
addPath(node.left, node.path);
tArray.push(node.left);
}
if(node.right) {
addPath(node.right, node.path);
tArray.push(node.right);
}
if(!(node.left || node.right)) {
paths.push(node.path);
}
}
temp = tArray;
}
return paths;
};
const addPath = (node, basePath) => {
node.path = basePath + '->' + node.val;
}
执行用时 : 88 ms, 在所有 JavaScript 提交中击败了43.45%的用户
内存消耗 : 35.1 MB, 在所有 JavaScript 提交中击败了6.00%的用户