257.二叉树的所有路径【简单题】
题目链接
const initTree = (inputList) => {
const total = inputList.length;
if(!inputList[0])return null;
inputList[0] = new TreeNode(inputList[0]);
inputList.forEach((el,index) => {
let leftP = null;
let rightP = null;
if (el === null) return;
if (index*2+1 < total) {
leftP = inputList[index*2+1] !== null ? new TreeNode(inputList[index*2+1]): null;
inputList[index*2+1] = leftP;
}
if (index*2+2 < total) {
rightP = inputList[index*2+2] !== null ? new TreeNode(inputList[index*2+2]): null;
inputList[index*2+2] = rightP;
}
inputList[index].left = leftP;
inputList[index].right = rightP;
});
return inputList[0];
}
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
const getAllPath = (curNode, curPath, paths) => {
curPath.push(curNode.val)
if (!curNode.left && !curNode.right) {
paths.push(curPath);
return
}
if(curNode.left)getAllPath(curNode.left, [...curPath], paths);
if(curNode.right)getAllPath(curNode.right, [...curPath], paths);
}
const formatted = (paths) => {
const res = [];
paths.forEach(list=>{
res.push(list.join('->'));
})
return res;
}
var binaryTreePaths = function(root) {
if (!root) return [];
const paths = [];
getAllPath(root, [], paths);
return formatted(paths);
};
(()=>{
const input = [];
const root = initTree(input);
console.log('root', root);
console.log('binaryTreePaths', binaryTreePaths(root));
})();