-
Notifications
You must be signed in to change notification settings - Fork 46
Open
Description
/**
* 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 res = [];
if(root === null) return res;
if(root.left === null && root.right === null){
res.push(String(root.val));
return res;
}
var leftS = binaryTreePaths(root.left);
for(var i=0;i<leftS.length;i++){
res.push(`${root.val}->${leftS[i]}`);
}
var rightS = binaryTreePaths(root.right);
for(var i=0;i<rightS.length;i++){
res.push(`${root.val}->${rightS[i]}`)
}
return res;
};
解题思路:递归调用。计算一个节点左子树的字符串数组,和右子树的字符串数组,并和本几点的值串联起来返回。
leetcode原题地址:https://leetcode-cn.com/problems/binary-tree-paths/description/