1/** 2 * @file 二叉树所有路径 3 */ 4 5type Tree = { 6 value: number; 7 left?: Tree; 8 right?: Tree; 9} 10const tree: Tree = { 11 value: 1, 12 left: { 13 value: 2, 14 right: { value: 5 } 15 }, 16 right: { value: 3 } 17}; 18function treePath(root: Tree): string[] { 19 // 补全此处代码 20 throw new Error('功能待实现'); 21} 22console.log(treePath(tree)) // [ '1->2->5', '1->3' ] 23 24export default {}
参考答案:
1/** 2 * @file 二叉树所有路径 3 */ 4 5type Tree = { 6 value: number; 7 left?: Tree; 8 right?: Tree; 9}; 10 11const tree: Tree = { 12 value: 1, 13 left: { 14 value: 2, 15 right: { value: 5 }, 16 }, 17 right: { value: 3 }, 18}; 19 20function treePath(root: Tree): string[] { 21 const answer: [] = []; 22 let tmp: [][] = []; 23 const travel = (r: Tree) => { 24 if (r == null) { 25 return; 26 } 27 //@ts-ignore 28 tmp.push(r.value); 29 if (r.left == null && r.right == null) { 30 //@ts-ignore 31 answer.push(tmp); 32 tmp = [tmp[0]]; 33 return; 34 } 35 if (r.left) travel(r.left); 36 if (r.right) travel(r.right); 37 }; 38 travel(root); 39 //@ts-ignore 40 return answer.map((t) => t.join("->")); 41} 42console.log(treePath(tree)); // [ '1->2->5', '1->3' ] 43 44export default {};
最近更新时间:2024-08-10