Here is the binary tree paths problem: Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
And here is my Javascript code:
/**
* 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) {
var paths = [];
if(!root) return [];
if(root.left == null && root.right == null){
if(paths.length == 0) return [""+root.val];
else return root.val;
}
else{
if(root.left) paths.push(root.val + "->" + binaryTreePaths(root.left))
if(root.right) paths.push(root.val + "->" + binaryTreePaths(root.right))
}
return paths;
};
Test Case:
Input:
[1,2,3,5,6]
Output:
["1->2->5,2->6","1->3"]
Expected:
["1->2->5","1->2->6","1->3"]
Why is my code's output not returning the full path of "1->2->6" ?
When you make a recursive call, your function will return an array. You can't just push the concatenation of that array with the prefix string; you need to iterate through each of the returned subpaths and build a separate path to push onto the array:
var binaryTreePaths = function(root) {
var paths = [];
if(!root) return [];
if(root.left == null && root.right == null){
if(paths.length == 0) return [""+root.val];
else return root.val;
}
else{
if(root.left)
binaryTreePaths(root.left).forEach(function(lp) {
paths.push(root.val + "->" + lp);
});
if(root.right)
binaryTreePaths(root.right).forEach(function(rp) {
paths.push(root.val + "->" + rp);
});
}
return paths;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.