二叉树的非递归遍历

preOrder

循环访问并将左孩子入栈
遇到 p = null , 要出栈, 并访问右孩子

  public static void preOrder(TreeNode p) {
    Stack<TreeNode> stack = new Stack<>();
    while (p != null || !stack.isEmpty()) {
      while (p != null) {
        visit(p);
        stack.push(p);
        p = p.left;
      }
      p = stack.pop();
      p = p.right;
    }
  }
inOrder

改变 visit() 的位置, 放到 pop下面

  public static void inOrder(TreeNode p) {
    Stack<TreeNode> stack = new Stack<>();
    while (p != null || !stack.isEmpty()) {
      while (p != null) {
        stack.push(p);
        p = p.left;
      }
      p = stack.pop();
      visit(p);
      p = p.right;
    }
  }
postOrder

观察后序遍历顺序是, 左-右-根
先序遍历顺序是, 根-左-右
用栈逆序, 右-左-根
再改变左右顺序, 左-右-根

  public static void postOrder(TreeNode p) {
    Stack<TreeNode> stack = new Stack<>();
    Stack<TreeNode> help = new Stack<>();
    while (p != null || !stack.isEmpty()) {
      while (p != null) {
        help.push(p);
        stack.push(p);
        p = p.right;
      }
      p = stack.pop();
      p = p.left;
    }
    while (!help.isEmpty()) {
      visit(help.pop());
    }
  }
层序遍历

队列实现, 同时维护两个变量:
currSize 表示当前行的剩余节点
nextSize 表示下一行的节点数量

  public static void levelOrder(TreeNode p) {
    if (p == null) return;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(p);
    int currSize = 1;
    int nextSize = 0;
    while (!queue.isEmpty()) {
      p = queue.poll();
      visit(p);
      currSize--;
      if (p.left != null) {
        queue.offer(p.left);
        nextSize++;
      }
      if (p.right != null) {
        queue.offer(p.right);
        nextSize++;
      }
      if (currSize == 0) {
        currSize = nextSize;
        nextSize = 0;
        System.out.println();
      }
    }
  }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值