算法基础:二叉树 前序、中序、后序

1、递归思路

public class OrderRecur {

    public static void main(String args){
        int[] array = {12,23,34,54,6,77,6,54,56,6,7,87,15,15,15};
        //数组转Node
        Node head = array2Node(array);
    }

    //前序
    public void preOrderRecur(Node head){
        if(head == null){
            return;
        }
        System.out.println(head.value);
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }

    //中序
    public void midOrderRecur(Node head){
        if(head == null){
            return;
        }
        midOrderRecur(head.left);
        System.out.println(head.value);
        midOrderRecur(head.right);
    }

    //后序
    public void posOrderRecur(Node head){
        if(head == null){
            return;
        }
        posOrderRecur(head.left);
        posOrderRecur(head.right);
        System.out.println(head.value);
    }
    
    public static class Node{
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    //数组转二叉树
    public static Node array2Node(int[] array){
        int lenth = array.length;
        Node head = new Node(array[0]);
        Node cur = head;
        int i = 0;
        while(i < lenth){
            cur.value = array[i];
            i = i+1;
            if(i >= lenth){
                break;
            }
            cur.left.value = array[i];
            i = i+1;
            if(i >= lenth){
                break;
            }
            cur.right.value = array[i];
        }
        return head;
    }
}

 

2、非递归思路(任何递归实现方法都可以用非递归方式实现)

前序:

    //非递归方式的前序排列
    public void preOrderWithoutRecur(Node head){
        if(head == null){
            return;
        }
        Stack<Node> stack = new Stack<Node>();
        stack.add(head);
        while(stack != null){
            head = stack.pop();
            System.out.println(head.value);
            if(head.right != null){
                stack.push(head.right);
            }
            if(head.left != null){
                stack.push(head.left);
            }
        }
    }

中序:

    //用非递归方式完成中序排列
    public void midOrderWithoutRecur(Node head){
        if(head == null){
            return;
        }
        Stack<Node> stack = new Stack<>();
        while(stack != null || head !=null){
            if(head != null){
                stack.push(head);
                head = head.left;
            }else{
                head = stack.pop();
                System.out.println(head.value);
                head = head.right;
            }
        }
    }

后序(略,有时间再补)

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值