1. // const _ = require('lodash');
    2. // function sayHello() {
    3. // console.log('Hello, World');
    4. // }
    5. // _.times(5, sayHello);
    6. // 有一棵二叉树,二叉树中有两个节点s和t,输出从s到t的最短有向路径。其中,‘U’代表向上,‘L’代表向左,‘R’代表向右
    7. // Example:
    8. // 1
    9. // / \
    10. // 2 3
    11. // / / \
    12. // 4 5 6
    13. // s = 4, t = 5, output: "UU RL" (4->2->1->3->5)
    14. // s = 4, t = 6, U R
    15. function test(root, s, t) {
    16. let result = [];
    17. // 面试官问递归的返回是什么,怎么考虑
    18. function walk(node, path) {
    19. if (node === null || node === undefined) {
    20. return;
    21. }
    22. if (node.val === s.val || node.val === t.val) {
    23. result.push(path);
    24. return true;
    25. }
    26. let r1= walk(node.left, [...path, 'L']);
    27. let r2 = walk(node.right, [...path, 'R']);
    28. if (r1 && r2) {
    29. let n = path.length; // 减去公共的首部
    30. result[0] = result.slice(n);
    31. result[1] = result.slice(n);
    32. }
    33. }
    34. walk(root, []);
    35. console.log(result);
    36. if (result.length === 2) {
    37. let tmp = result[0].map(() => 'U');
    38. return [...tmp, ...result[1]].join('');
    39. }
    40. if (result.length === 1) {
    41. let tmp = result[0].map(() => 'U');
    42. return tmp.join('');
    43. }
    44. return result;
    45. }
    46. function Node(val, left, right) {
    47. this.val = val;
    48. this.left = left;
    49. this.right = right;
    50. }
    51. // 1
    52. // / \
    53. // 2 3
    54. // / / \
    55. // 4 5 6
    56. const n1 = new Node(1);
    57. const n2 = new Node(2);
    58. const n3 = new Node(3);
    59. const n4 = new Node(4);
    60. const n5 = new Node(5);
    61. const n6 = new Node(6);
    62. n1.left = n2;
    63. n1.right = n3;
    64. n2.left = n4;
    65. n3.left = n5;
    66. n3.right = n6;
    67. // console.log(test(n1, n4, n2));
    68. console.log(test(n1, n5, n6));