1. const bt = {
    2. val: 1,
    3. left: {
    4. val: 2,
    5. left: {
    6. val: 4,
    7. left: null,
    8. right: null,
    9. },
    10. right: {
    11. val: 5,
    12. left: null,
    13. right: null,
    14. }
    15. },
    16. right: {
    17. val: 3,
    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. }
    1. //先序遍历
    2. const preorder = (root) => {
    3. if (!root) { return }
    4. const stack = [root];
    5. while (stack.length > 0) {
    6. const n = stack.pop()
    7. console.log(n.val)
    8. if (n.right) stack.push(n.right)
    9. if (n.left) stack.push(n.left)
    10. }
    11. }

    二叉树,先中后遍历非递归版 - 图1

    1. //中序遍历
    2. const inorder = (root) => {
    3. if (!root) return
    4. const stack = [];
    5. let p = root;
    6. while (stack.length || p) {
    7. while (p) {
    8. stack.push(p);
    9. p = p.left
    10. }
    11. const n = stack.pop()
    12. console.log(n.val)
    13. p = n.right
    14. }
    15. }

    二叉树,先中后遍历非递归版 - 图2

    1. //后序遍历
    2. const postorder = (root) => {
    3. if (!root) return
    4. const stack = [root]
    5. const res = []
    6. while (stack.length) {
    7. const n = stack.pop()
    8. res.push(n)
    9. if (n.left) stack.push(n.left)
    10. if (n.right) stack.push(n.right)
    11. }
    12. while(res.length){
    13. const n = res.pop()
    14. console.log(n.val)
    15. }
    16. }