二叉树的相关代码

1、二叉树的先序,中序,后序遍历

import java.util.Stack;
/**
 * @Author zb
 * @Date 2018/8/14
 * 二叉树的先序,中序,后序遍历
 */
public class PreInPosTraversal {

    /**
     * 定义二叉树结点
     */
    public static class Node{
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    /**
     * 递归实现先序遍历
     * @param head
     */
    public static void preOrderRecur(Node head){
        if(head == null){
            return ;
        }
        System.out.print(head.value + " ");
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }

    /**
     * 递归实现中序遍历
     * @param head
     */
    public static void inOrderRecur(Node head){
        if(head == null){
            return ;
        }
        inOrderRecur(head.left);
        System.out.print(head.value + " ");
        inOrderRecur(head.right);
    }

    /**
     * 递归实现后序遍历
     * @param head
     */
    public static void posOrderRecur(Node head){
        if(head == null){
            return ;
        }
        posOrderRecur(head.left);
        posOrderRecur(head.right);
        System.out.print(head.value + " ");
    }

    /**
     * 非递归实现先序遍历
     * @param head
     */
    public static void preOrderUnRecur(Node head){
        System.out.println("pre-order: ");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            //向栈中添加头结点
            stack.add(head);
            //当前结点
            Node cur;
            while(!stack.isEmpty()){
                cur = stack.pop();
                System.out.print(cur.value + " ");
                //注意:如果不为空,先压右,再压左(弹栈打印的时候才会是先左后右)
                if(cur.right != null){
                    stack.push(cur.right);
                }
                if(cur.left != null){
                    stack.push(cur.left);
                }
            }
        }
        System.out.println();
    }

    /**
     * 非递归实现中序遍历
     * @param head
     */
    public static void inOrderUnRecur(Node head){
        System.out.println("in-order:");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            Node cur = head;
            //当前结点为空:从栈中拿一个打印,当前结点向右跑
            //当前结点不为空,当前结点压入栈,当前结点向左跑
            while(!stack.isEmpty() || cur != null){
                if(cur != null){
                    stack.push(cur);
                    cur = cur.left;
                }else{
                    cur = stack.pop();
                    System.out.print(cur.value + " ");
                    cur = cur.right;
                }
            }
        }
        System.out.println();
    }

    /**
     * 非递归实现后序遍历(两个栈)
     * @param head
     */
    public static void posOrderUnRecur1(Node head){
        System.out.println("pos-order:");
        if(head != null){
            Stack<Node> s1 = new Stack<Node>();
            Stack<Node> s2 = new Stack<Node>();
            s1.push(head);
            Node cur = head;
            //根据先序遍历(中左右)的代码,求出(中右左),再根据栈的特性,逆过来就是后序(左右中)
            //s2作为辅助栈,把先序遍历中要打印的结点,先压入栈中,最后打印,即为左右中
            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()){
                System.out.print(s2.pop().value + " ");
            }
        }
        System.out.println();
    }

    /**
     * 非递归实现后序遍历(一个栈)
     * @param head
     */
    public static void posOrderUnRecur2(Node head){
        System.out.println("pos-order:");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            stack.push(head);
            Node cur = null;
            while(!stack.isEmpty()){
                cur = stack.peek();
                if(cur.left != null && head != cur.left && head != cur.right){
                    stack.push(cur.left);
                }else if(cur.right != null && head != cur.right){
                    stack.push(cur.right);
                }else {
                    System.out.print(stack.pop().value + " ");
                    head = cur;
                }
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);

        // 递归实现
        System.out.println("==============recursive==============");
        System.out.print("pre-order: ");
        preOrderRecur(head);
        System.out.println();
        System.out.print("in-order: ");
        inOrderRecur(head);
        System.out.println();
        System.out.print("pos-order: ");
        posOrderRecur(head);
        System.out.println();

        //非递归实现
        System.out.println("============unrecursive=============");
        preOrderUnRecur(head);
        inOrderUnRecur(head);
        posOrderUnRecur1(head);
        posOrderUnRecur2(head);
    }

}

2、二叉树的序列化与反序列化

import java.util.LinkedList;
import java.util.Queue;
/**
 * @Author zb
 * @Date 2018/8/14
 * 二叉树的序列化与反序列化
 */
public class SerializeTree {

    public static class Node {
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    /**
     * 先序的序列化
     * 如果结点的值不为空用!隔离,如果为用#!
     * @param head
     * @return
     */
    public static String serialByPre(Node head){
        if(head == null){
            return "#!";
        }
        String res = head.value + "!";
        res += serialByPre(head.left);
        res += serialByPre(head.right);
        return res;
    }

    /**
     * 先序的反序列化
     * @param preStr
     * @return
     */
    public static Node reconByPreString(String preStr){
        String[] values = preStr.split("!");
        Queue<String> queue = new LinkedList<String>();
        for(int i = 0; i != values.length; i++){
            queue.offer(values[i]);
        }
        return reconPreOrder(queue);
    }

    /**
     * 先序的反序列化方法
     * @param queue
     * @return
     */
    public static Node reconPreOrder(Queue<String> queue){
        String value = queue.poll();
        if(value.equals("#")){
            return null;
        }
        Node head = new Node(Integer.valueOf(value));
        head.left = reconPreOrder(queue);
        head.right = reconPreOrder(queue);
        return head;
    }


    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.right.right = new Node(5);
        System.out.println(serialByPre(head));

    }

}

3、判断平衡二叉树

/**
 * @Author zb
 * @Date 2018/8/15
 */
public class IsBalanceTree {

    public static class Node {
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    /**
     * 定义递归结构
     * isB:返回是否为平衡树
     * h:返回树的高度
     */
    public static class ReturnData{
        public boolean isB;
        public int h;
        public ReturnData(boolean isB, int h){
            this.isB = isB;
            this.h = h;
        }
    }

    /**
     * 递归过程
     * 判断一棵树是否为平衡二叉树的思路:
     * 对于任意结点,左子树是否平衡,右子树是否平衡,
     * 左子树和右子树的高度差是否不超过1
     * @param head
     * @return
     */
    public static ReturnData process(Node head){
        if(head == null){
            //空树也是平衡树
            return new ReturnData(true,0);
        }

        //返回当前结点的左树信息
        ReturnData leftData = process(head.left);
        if(!leftData.isB){
            //如果左树不平衡,返回false
            return new ReturnData(false,0);
        }

        //返回当前结点的右树信息
        ReturnData rightData = process(head.right);
        if(!rightData.isB){
            //如果右树不平衡,返回false
            return new ReturnData(false,0);
        }

        //左树和右树高度差大于1,返回false
        if(Math.abs(leftData.h - rightData.h) > 1){
            return new ReturnData(false,0);
        }
        return new ReturnData(true,Math.max(leftData.h, rightData.h)+1);
    }

    /**
     * 主函数:判断是否为平衡二叉树
     * @param head
     * @return
     */
    public static boolean isBTree(Node head){
        return process(head).isB;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.left.left = new Node(7);
        System.out.println(isBTree(head));
    }

}

4、判断二叉搜索树

import java.util.Stack;
/**
 * @Author zb
 * @Date 2018/8/15
 * 什么叫搜索二叉树:任何一个结点的左子树都比他小,右子树都比他大
 */
public class IsBST {

    public static class Node{
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    /**
     * 判断是否为二叉搜索树方法一:Morris遍历
     * @param head
     * @return
     */
    public static boolean isBST1(Node head){
        if(head == null){
            return true;
        }
        boolean res = true;
        Node pre = null;
        Node cur1 = head;
        Node cur2 = null;
        while(cur1 != null){
            cur2 = cur1.left;
            if(cur2 != null){
                while (cur2.right != null && cur2.right != cur1) {
                    cur2 = cur2.right;
                }
                if (cur2.right == null) {
                    cur2.right = cur1;
                    cur1 = cur1.left;
                    continue;
                } else {
                    cur2.right = null;
                }
            }
            if (pre != null && pre.value > cur1.value) {
                res = false;
            }
            pre = cur1;
            cur1 = cur1.right;
        }
        return res;
    }

    /**
     * 判断是否为二叉搜索树方法二:中序遍历
     *   二叉树在中序遍历情况下是依次升序的就是搜索二叉树,
     *   否则就不是搜索二叉树
     */
    //定义上一个结点的值
    static int lastNodeValue = Integer.MIN_VALUE;
    public static boolean isBST2(Node head){
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            Node cur = head;
            while(!stack.isEmpty() || cur != null){
                if(cur != null){
                    stack.push(cur);
                    cur = cur.left;
                }else{
                    cur = stack.pop();
                    //升序判断,用上一个值和当前值比较
                    if(cur.value <= lastNodeValue){
                        return false;
                    }
                    lastNodeValue = cur.value;
                    cur = cur.right;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Node head = new Node(4);
        head.left = new Node(2);
        head.right = new Node(6);
        head.left.left = new Node(1);
        head.left.right = new Node(3);
        head.right.left = new Node(5);
        System.out.println(isBST1(head));
        System.out.println(isBST2(head));
    }

}

5、判断完全二叉树

import java.util.LinkedList;
import java.util.Queue;
/**
 * @Author zb
 * @Date 2018/8/15
 */
public class IsCompleteTree {

    public static class Node{
        public int value;
        public Node left;
        public Node right;
        public Node(int data){
            this.value = data;
        }
    }

    /**
     * 判断是否为完全二叉树的思路:
     * 1、如果当前结点的左孩子为空,右孩子不为空,返回false
     * 2、如何当前结点的左孩子或右孩子有一个为空,或都为空(此次用一个变量标识,如果满足条件,
     * 则开启判断叶子结点的阶段),则后面的结点都是叶子结点
     * @param head
     * @return
     */
    public static boolean isComTree(Node head){
        if(head == null){
            return true;
        }
        Queue<Node> queue = new LinkedList<Node>();
        //是否开启验证叶子结点阶段
        boolean leaf = false;
        Node leftChild = null;
        Node rightChild = null;
        Node cur = null;
        queue.offer(head);
        while (!queue.isEmpty()){
            //当前结点
            cur = queue.poll();
            //当前结点的左孩子
            leftChild = cur.left;
            //当前结点的有孩子
            rightChild = cur.right;

            //如果左孩子为空,右孩子不为空,返回false
            //如何开启了结点验证阶段,l或者r不为空,返回false
            if((leaf && (leftChild != null || rightChild != null)) || (leftChild == null && rightChild != null)){
                return false;
            }
            //宽度遍历(先判断左边,再判断右边)
            if(leftChild != null){
                queue.offer(leftChild);
            }
            if(rightChild != null){
                queue.offer(rightChild);
            }
            if(leftChild == null || rightChild == null){
                leaf = true;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Node head = new Node(4);
        head.left = new Node(2);
        head.left.left = new Node(1);
        head.left.right = new Node(3);
        System.out.println(isComTree(head));
    }

}

6、二叉树按层打印

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
 * @Author zb
 * @Date 2018/9/4
 * 【树】把二叉树打印成多行
 *
 * 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
 */
public class Demo60 {

    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
        if(pRoot == null){
            return lists;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        //当前行的最后节点
        TreeNode last = pRoot;
        //下一行的最右节点
        TreeNode nlast = pRoot;
        queue.add(pRoot);
        ArrayList<Integer> list = new ArrayList<Integer>();
        while(!queue.isEmpty()){
            TreeNode out = queue.poll();
            list.add(out.val);
            if(out.left != null){
                queue.add(out.left);
                nlast = out.left;
            }
            if(out.right != null){
                queue.add(out.right);
                nlast = out.right;
            }
            if(out == last){
                //当前行打印完毕
                lists.add(list);
                last = nlast;
                list = new ArrayList<Integer>();
            }
        }
        return lists;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值