二叉树的非递归遍历

二叉树的遍历主要分三种,分别是先序、中序、后序。

如果按搜索的话可分为bfs(广度优先搜索)和dfs(深度优先搜索),前者基于队列后者基于栈,在处理树和图的时候比较常用。

再来说先序、中序、后序三种遍历的区别:

  • 先序 父->左->右
  • 中序 左->父->右
  • 后序 左->右->父

如果使用递归很简单,我们可以使用递归栈的特性,轻松实现树的先中后序遍历,如下

//先序
private static void pre(Node root) {
    System.out.println(root.val);
    if(root.left  != null) {
        pre(root.left);
    }
    if(root.right != null) {
        pre(root.right);
    }
}


//中序
private static void mid(Node root) {
    if(root.left  != null) {
        mid(root.left);
    }
    System.out.println(root.val);
    if(root.right != null) {
        mid(root.right);
    }
}

//后序
private static void after(Node root) {
    if(root.left  != null) {
        after(root.left);
    }
    if(root.right != null) {
        after(root.right);
    }
    System.out.println(root.val);
}

很容易发现三种遍历方式的区别只是打印当前节点的这样代码位置的变动,几行代码就能轻松实现;

而要是使用非递归呢,因为上面代码是利用的递归的特性,即栈。那么不实用递归我们就需要自己来维护一个栈。

 

先序

其实while循环里面的语句跟非递归先序遍历的代码类似,只是我们需要手动维护栈。

//先序
private static void pre(Node root) {
    Stack<Node> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        Node node = stack.pop();
        System.out.println(node.val);
        if (node.right != null) {
            stack.push(node.right);
        }
        if (node.left != null) {
            stack.push(node.left);
        }
    }
}

中序

//中序
private static void mid(Node root) {
    Stack<Node> stack = new Stack<>();
    Node node = root;
    while (node != null || !stack.isEmpty()) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
        node = stack.pop();
        System.out.println(node.val);
        node = node.right;
    }
}

后序

后序的非递归实现本身比较麻烦,但是在做leetcode的时候看到了这个方法比较巧,巧在灵活运用了链表头插尾删这些特点(讲真,之前不知道LinkedList有pollLast和addFirst方法)。这样写出来感觉跟先序遍历差不多,但是要注意链表插节点和取节点的位置,理解着记忆。

//  后序
private static void after(Node root) {
    LinkedList<Node> stack = new LinkedList<>();
    LinkedList<Integer> output = new LinkedList<>();
    stack.add(root);
    while (!stack.isEmpty()) {
        Node node = stack.pollLast();
        output.addFirst(node.val);
        if (node.left != null) {
            stack.add(node.left);
        }
        if (node.right != null) {
            stack.add(node.right);
        }
    }
    System.out.println(output);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值