257. Binary Tree Paths
Leetcode
題目
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]Input: root = [1]
Output: ["1"]è§£ç”
Last updated
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]Input: root = [1]
Output: ["1"]Last updated
var binaryTreePaths = function(root) {
if(root === null) return [];
const res = [];
const queue = [{
val: [],
node: root
}];
while(queue.length) {
const curr = queue.shift();
const node = curr.node;
const val = [...curr.val, node.val];
if (!node.left && !node.right) res.push(val.join('->'));
if (node.left) {
queue.push({
val,
node: node.left
})
}
if (node.right) {
queue.push({
val,
node: node.right
})
}
}
return res;
};var binaryTreePaths = function(root) {
const res = [];
const helper = (node, path) => {
if (!node) return;
path += node.val.toString();
if (!node.left && !node.right) res.push(path);
path += "->"
helper(node.left, path);
helper(node.right, path);
}
helper(root, '');
return res;
};