二叉树

常考:
1. 能够结合队列、栈、链表、字符串等许多数据结构。
2. 需要掌握图的基本遍历方式,比如BFS、DFS。
3. 需要掌握递归函数的使用,并自己设计出递归过程。
4. 与实际工作紧密结合。


二叉树遍历


  • 中前后(前序)
  • 前中后(中序)
  • 前后中(后序)

前序遍历
// 递归方式
public void PreOrderRecur(Node head){
    if(head == null)
        return;
    System.out.println(head.val+" ");
    PreOrderRecur(head.left);
    PreOrderRecur(head.right);
}

PreOrderUnRecur

public void PreOrderUnRecur(Node head){
    if(head == null)
        return;
    Stack<Node> stack = new Stack<Node>();
    stack.push(head);
    while(!stack.isEmpty()){
        Node cur = stack.pop();
        System.out.println(cur.val+" ");
        if(cur.right != null)
            stack.push(cur.right);
        if(cur.left != null)
            stack.push(cur.left);
    }
}

中序遍历
// 递归方式
public void InOrderRecur(Node head){
    if(head == null)
        return;
    InOrderRecur(head.left);
    System.out.println(head.val+" ");
    InOrderRecur(head.right);
}

InOrderUnRecur

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

后序遍历
// 递归方式
public void PosOrderRecur(Node head){
    if(head == null)
        return;
    PosOrderRecur(head.left);
    PosOrderRecur(head.right);
    System.out.println(head.val+" ");
}

PosOrderUnRecur1

public void PosOrderUnRecur(Node head){
    if(head == null)
        return;
    Stack<Node> s1 = new Stack<Node>();
    Stack<Node> s2 = new Stack<Node>();
    Node cur = head;
    s1.push(cur);
    while (!s1.isEmpty()) {
        cur = s1.pop();
        s2.push(cur);
        if(cur.left != null)
            s1.push(cur.left);
        if(cur.right != null)
            s1.push(cur.right);
    }
    while (!s2.isEmpty()){
        cur = s2.pop();
        System.out.println(cur.val+" ");
    }
}

PosOrderUnRecur2

public void PosOrderUnRecur(Node head){
    if(head == null)
        return;
    Stack<Node> stack = new Stack<Node>();
    stack.push(head);
    Node h = head;
    Node c = null;
    while(!stack.isEmpty()){
        c = stack.peek();
        if(c.left != null && h != c.left && h != c.right)
            stack.push(c.left);
        else if(c.right != null && h != c.right)
            stack.push(c.right);
        else {
            System.out.println(stack.pop().val+" ");
            h = c;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值