先、中、后序遍历

    1. const tree = {
    2. val: 1,
    3. left: {
    4. val: 2,
    5. left: {
    6. val: 3,
    7. left: null,
    8. right: null,
    9. },
    10. right: {
    11. val: 4,
    12. left: null,
    13. right: null,
    14. }
    15. },
    16. right: {
    17. val: 5,
    18. left: {
    19. val: 6,
    20. left: null,
    21. right: null,
    22. },
    23. right: {
    24. val: 7,
    25. left: null,
    26. right: null,
    27. }
    28. }
    29. }
    30. // // 根,左,右
    31. // const preorder = (root) => {
    32. // if(!root) {return }
    33. // console.log(root.val);
    34. // preorder(root.left);
    35. // preorder(root.right);
    36. // }
    37. // preorder(tree);
    38. // 左,根, 右,
    39. // const inorder = (root) => {
    40. // if(!root) {return }
    41. // inorder(root.left);
    42. // console.log(root.val);
    43. // inorder(root.right);
    44. // }
    45. // inorder(tree);
    46. // 左, 右,根,
    47. const postorder = (root) => {
    48. if(!root) {return }
    49. postorder(root.left);
    50. postorder(root.right);
    51. console.log(root.val);
    52. }
    53. postorder(tree);
    54. // ========================================== 非递归
    55. // 前序 根,左,右
    56. // const preorder = (root) => {
    57. // if(!root) {return }
    58. // const stack = [root];
    59. // while(stack.length) {
    60. // const n = stack.pop();
    61. // console.log(n.val);
    62. // // 栈是先进后出,所以我们先把右节点push进去
    63. // if(n.right) stack.push(n.right)
    64. // if(n.left) stack.push(n.left)
    65. // }
    66. // }
    67. // preorder(tree);
    68. // 中序左,根, 右,
    69. // const inorder = (root) => {
    70. // if(!root) {return }
    71. // const stack = [];
    72. // let p = root;
    73. // while(stack.length || p) {
    74. // while(p) {
    75. // stack.push(p);
    76. // p = p.left
    77. // }
    78. // const n = stack.pop();
    79. // console.log(n.val);
    80. // p = n.right
    81. // }
    82. // }
    83. // inorder(tree);
    84. // 后序 左, 右,根,
    85. const postorder = (root) => {
    86. if(!root) {return }
    87. const stack = [root];
    88. const outPutStack = [];
    89. while(stack.length) {
    90. const n = stack.pop();
    91. outPutStack.push(n)
    92. // 栈是先进后出,所以我们先把右节点push进去
    93. if(n.left) stack.push(n.left)
    94. if(n.right) stack.push(n.right)
    95. }
    96. while(outPutStack.length) {
    97. const n = outPutStack.pop();
    98. console.log(n.val);
    99. }
    100. }
    101. postorder(tree);