左程云基础班——二叉树

这篇博客主要讲解了二叉树的遍历方法,包括前序、后序、中序和宽度遍历,以及如何判断二叉查找树、完全二叉树和满二叉树。还包含了几个相关的练习题,如寻找最近公共父节点和微软折纸面试题等。
摘要由CSDN通过智能技术生成

左程云基础班——二叉树

1. 遍历二叉树

二叉树结点:

public class Node {
   
    public int value;
    public Node left;
    public Node right;

    public Node(int value) {
   
        this.value = value;
    }
}

1)前序遍历

	public static void preOrderRecur(Node head) {
   
        if (head == null) {
   
            return;
        }
        
        System.out.print(head.value + " ");
        
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }
    
    public static void preOrderUnRecur(Node head) {
   
        if (head != null) {
   
        	//入栈顺序根右左
            Stack<Node> stack = new Stack<>();
            stack.push(head);
            while (!stack.isEmpty()) {
   
                head = stack.pop();
                
                System.out.print(head.value + " ");
                
                if (head.right != null) {
   
                    stack.push(head.right);
                }
                if (head.left != null) {
   
                    stack.push(head.left);
                }
            }
        }
    }

2)后序遍历

	public static void postOrderRecur(Node head) {
   
        if (head == null) {
   
            return;
        }
        postOrderRecur(head.left);
        postOrderRecur(head.right);
        
        System.out.print(head.value + " ");
    }
    //入栈顺序根左右,逆序输出
    public static void postOrderUnRrecur(Node head) {
   
        if (head != null) {
   
            Stack<Node> stack = new Stack<>();
            Stack<Node> res = new Stack<>();
            stack.push(head);
            while (!stack.isEmpty()) {
   
                head = stack.pop();
                res.push(head);
                if (head.left != null) {
   
                    stack.push(head.left);
                }
                if (head.right != null) {
   
                    stack.push(head.right);
                }
            }
            while (!res.isEmpty()) {
   
                
                System.out.print(res.pop().value + " ");
                
            }
        }
    }

3)中序遍历

	public static void inOrderRecur(Node head) {
   
        if (head == null) {
   
            r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值