二叉树的先中后序遍历递归和非递归

题目描述

实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式

实现

递归方式

public static class Node {
    int val;
    Node left;
    Node right;

    public Node(int data) {
        this.val = data;
    }

}

// 前序递归
public static void preTraversal(Node head) {
    if (head == null) return;

    System.out.print(head.val + " ");
    preTraversal(head.left);
    preTraversal(head.right);
}

// 中序递归
public static void inTraversal(Node head) {
    if (head == null) return;
    inTraversal(head.left);
    System.out.print(head.val + " ");
    inTraversal(head.right);
}

// 后序递归
public static void posTraversal(Node head) {
    if (head == null) return;

    posTraversal(head.left);
    posTraversal(head.right);
    System.out.print(head.val + " ");
}



非递归方式

前序

使用栈结构来实现,注意压栈先压右孩子,这样出栈顺序后出右孩子。

 // 前序非递归
    public static void preTravelsal1(Node head) {
        if (head == null) return;

        Stack<Node> stack = new Stack<>();
        Node node = root;
        while (node != null ||!stack.isEmpty()) {
           if(node != null){
           		System.out.print(node.val+"-->");
           		stack.push(node);
           		node = node.left;	
           }else{
				
			}
        }
    }
中序

利用栈结构来实现。

  • 当前节点不为空,压入栈,当前节点为左孩子
  • 当前节点为空,从栈中拿一个,当前节点为右孩子
// 中序非递归
    public static void inTravelsal1(Node head) {
        if (head == null) return;

        Stack<Node> stack = new Stack<>();
        while (!stack.isEmpty() || head != null) {
            if (head != null) {
                stack.push(head);
                head = head.left;
            } else {
                head = stack.pop();
                System.out.print(head.val + " ");
                head = head.right;
            }
        }
    }

判断一棵树是否为二叉搜索树可以通过中序遍历实现

后序

前序遍历是根左右,后序遍历是左右根。
那么在非递归版本中很容易将根左右顺序,换成根右左顺序。然后在每次前序遍历输出打印的地方,把当前节点存入到第二个栈中:根右左。
最后将第二个栈中的数据一个个弹出来的时候,就是左右根的顺序

// 后序非递归
    public static void posTravelsal(Node head){
        if(head == null) return;

        Stack<Node> s1 = new Stack<>();
        Stack<Node> s2 = new Stack<>();
        s1.push(head);
        while(!s1.isEmpty()){
            head = s1.pop();
            s2.push(head);
            if(head.left != null) s1.push(head.left);
            if(head.right != null) s1.push(head.right);
        }
        while(!s2.isEmpty()){
            System.out.print(s2.pop().val + " ");
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值