重新定义与理解二叉树

128 阅读8分钟

为什么需要树这种数据结构

数组存储方式的分析 优点:通过下标方式访问元素,速度快。对于有序数组,还可使用二分查找提高检索速度。

缺点:如果要检索具体某个值,或者插入值(按一定顺序)会整体移动,效率较低

链式存储方式的分析

优点:在一定程度上对数组存储方式有优化(比如:插入一个数值节点,只需要将插入节点,链接到链表中即可, 删除效率也很好)。

缺点:在进行检索时,效率仍然较低,比如(检索某个值,需要从头节点开始遍历)

树存储方式的分析

能提高数据存储,读取的效率,比如利用二叉排序树(BinarySortTree),既可以保证数据的检索速度,同时也可以保证数据的插入,删除,修改的速度。

案例: [7, 3, 10, 1, 5, 9, 12]

树的常用术语(结合示意图理解):

树有很多种,每个节点最多只能有两个子节点的一种形式称为二叉树。

根节点

父节点

子节点:二叉树的子节点分为左节点和右节点。

叶子节点 (没有子节点的节点)

节点的权(节点值)

路径(从root节点找到该节点的路线)

树的高度(最大层数)

森林 :多颗子树构成森林

满二叉树: 如果该二叉树的所有叶子节点都在最后一层,并且结点总数=2^n-1,n为层数,则我们称为满二叉树。

完全二叉树:如果该二叉树的所有叶子节点都在最后一层或者倒数第二层,而且最后一层的叶子节点在左边连续,倒数第二层的叶子节点在右边连续,我们称为完全二叉树。

树的前序中序后序遍历

前序遍历: 先输出父节点,再遍历左子树和右子树

中序遍历: 先遍历左子树,再输出父节点,再遍历右子树

后序遍历: 先遍历左子树,再遍历右子树,最后输出父节点

小结: 看输出父节点的顺序,就确定是前序,中序还是后序

思路

代码实现

 public static void main(String[] args) {
        //先需要创建一颗二叉树
        BinaryTree binaryTree = new BinaryTree();
        //创建需要的结点
        HeroNode root = new HeroNode(1, "宋江");
        HeroNode node2 = new HeroNode(2, "吴用");
        HeroNode node3 = new HeroNode(3, "卢俊义");
        HeroNode node4 = new HeroNode(4, "林冲");
        HeroNode node5 = new HeroNode(5, "关胜");

        //说明,我们先手动创建该二叉树,后面我们学习递归的方式创建二叉树
        root.setLeft(node2);
        root.setRight(node3);
        node3.setRight(node4);
        node3.setLeft(node5);
        binaryTree.setRoot(root);

        //测试
		System.out.println("前序遍历"); // 1,2,3,5,4
		binaryTree.preOrder();

        //测试
		System.out.println("中序遍历");
		binaryTree.infixOrder(); // 2,1,5,3,4

		System.out.println("后序遍历");
		binaryTree.postOrder(); // 2,5,4,3,1
    }

    //创建二叉树
    static class BinaryTree{

        HeroNode root;

        public HeroNode getRoot() {
            return root;
        }

        public void setRoot(HeroNode root) {
            this.root = root;
        }

        public BinaryTree() {
        }

        //前序遍历
        public void preOrder() {
            if(this.root != null) {
                this.root.preOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }

        //中序遍历
        public void infixOrder() {
            if(this.root != null) {
                this.root.infixOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
        //后序遍历
        public void postOrder() {
            if(this.root != null) {
                this.root.postOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
    }

    //创建结点node
    static class HeroNode{
        int no;
        String name;
        HeroNode left;
        HeroNode right;

        public HeroNode() {
        }

        public HeroNode(int no, String name) {
            this.no = no;
            this.name = name;
        }

        @Override
        public String toString() {
            return "HeroNode{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    '}';
        }

        /**
         * 前序遍历
         */
        public void preOrder(){
            System.out.println(this);
            if(this.left != null){
                this.left.preOrder();
            }
            if(this.right != null){
                this.right.preOrder();
            }
        }

        /**
         * 中序遍历
         */
        public void infixOrder(){
            if(this.left!=null){
                this.left.infixOrder();
            }
            System.out.println(this);
            if(this.right !=null){
                this.right.infixOrder();
            }
        }

        /**
         * 后序遍历
         */
        public void postOrder(){
            if(this.left!=null){
                this.left.postOrder();
            }

            if(this.right !=null){
                this.right.postOrder();
            }
            System.out.println(this);
        }
    }
}

结果展示:

前序、中序、后序遍历查找方式

思路分析

代码分析

 //创建二叉树
    static class BinaryTree{

        HeroNode root;

        public HeroNode getRoot() {
            return root;
        }

        public void setRoot(HeroNode root) {
            this.root = root;
        }

        public BinaryTree() {
        }

    .......

        //前序遍历查找
        public HeroNode preOrderSearch(int no) {
            if(root != null) {
                return root.preOrderSearch(no);
            } else {
                return null;
            }
        }
        //中序遍历查找
        public HeroNode infixOrderSearch(int no) {
            if(root != null) {
                return root.infixOrderSearch(no);
            }else {
                return null;
            }
        }
        //后序遍历查找
        public HeroNode postOrderSearch(int no) {
            if(root != null) {
                return this.root.postOrderSearch(no);
            }else {
                return null;
            }
        }
    }
    
 //创建结点node
    static class HeroNode{
        int no;
        String name;
        HeroNode left;
        HeroNode right;

        public HeroNode() {
        }

        /**
         * 前续遍历查找
         * @param no
         * @return
         */
        public HeroNode preOrderSearch(int no) {

            if(this.no == no){
                return this;
            }

            HeroNode heroNode=null;
            System.out.println("进入前序遍历");
            if(this.left != null){
                heroNode = this.left.preOrderSearch(no);
            }
            if(heroNode != null){
                return heroNode;
            }

            if(this.right != null){
                heroNode = this.right.preOrderSearch(no);
            }
            return heroNode;
        }

        /**
         * 中续遍历查找
         * @param no
         * @return
         */
        public HeroNode infixOrderSearch(int no) {

            HeroNode heroNode=null;
            if(this.left != null){
                heroNode = this.left.infixOrderSearch(no);
            }

            if(heroNode!=null){
                return heroNode;
            }
            System.out.println("进入中序遍历查找");
            if(this.no == no){
                return this;
            }

            if(this.right != null){
                heroNode = this.right.infixOrderSearch(no);
            }
            return heroNode;
        }

        /**
         * 后续遍历查找
         * @param no
         * @return
         */
        public HeroNode postOrderSearch(int no) {

            HeroNode heroNode=null;
            if(this.left != null){
                heroNode = this.left.postOrderSearch(no);
            }
            if(heroNode!=null){
                return heroNode;
            }

            if(this.right != null){
                heroNode = this.right.postOrderSearch(no);
            }
            if(heroNode!=null){
                return heroNode;
            }
            System.out.println("进入后续遍历查找");
            if(this.no == no){
                return this;
            }
            return heroNode;
        }
    }    

运行代码

public static void main(String[] args) {
        //先需要创建一颗二叉树
        BinaryTree binaryTree = new BinaryTree();
        //创建需要的结点
        HeroNode root = new HeroNode(1, "宋江");
        HeroNode node2 = new HeroNode(2, "吴用");
        HeroNode node3 = new HeroNode(3, "卢俊义");
        HeroNode node4 = new HeroNode(4, "林冲");
        HeroNode node5 = new HeroNode(5, "关胜");

        //说明,我们先手动创建该二叉树,后面我们学习递归的方式创建二叉树
        root.setLeft(node2);
        root.setRight(node3);
        node3.setRight(node4);
        node3.setLeft(node5);
        binaryTree.setRoot(root);

        //测试
		System.out.println("前序遍历"); // 1,2,3,5,4
		binaryTree.preOrder();

        //测试
		System.out.println("中序遍历");
		binaryTree.infixOrder(); // 2,1,5,3,4

		System.out.println("后序遍历");
		binaryTree.postOrder(); // 2,5,4,3,1

        //前序遍历
        //前序遍历的次数 :4
		System.out.println("前序遍历方式~~~");
		HeroNode resNode = binaryTree.preOrderSearch(5);
		if (resNode != null) {
			System.out.printf("找到了,信息为 no=%d name=%s", resNode.getNo(), resNode.getName());
            System.out.println();
		} else {
			System.out.printf("没有找到 no = %d 的英雄", 5);
            System.out.println();
		}
        System.out.println();

        //中序遍历查找
        //中序遍历3次
		System.out.println("中序遍历方式~~~");
		HeroNode resNode2 = binaryTree.infixOrderSearch(5);
		if (resNode != null) {
			System.out.printf("找到了,信息为 no=%d name=%s", resNode2.getNo(), resNode2.getName());
            System.out.println();
		} else {
			System.out.printf("没有找到 no = %d 的英雄", 5);
            System.out.println();
		}

        //后序遍历查找
        //后序遍历查找的次数  2次
		System.out.println("后序遍历方式~~~");
		HeroNode resNode3 = binaryTree.postOrderSearch(5);
		if (resNode != null) {
			System.out.printf("找到了,信息为 no=%d name=%s", resNode3.getNo(), resNode3.getName());
            System.out.println();
		} else {
			System.out.printf("没有找到 no = %d 的英雄", 5);
            System.out.println();
		}
    }

运行结果

可以结合这张图,比较不会迷惑:

删除二叉树指定节点

思路分析

代码实现

//递归删除结点
	//1.如果删除的节点是叶子节点,则删除该节点
	//2.如果删除的节点是非叶子节点,则删除该子树
public void delNode(int no) {
		
		//思路
		/*
		 * 	1. 因为我们的二叉树是单向的,所以我们是判断当前结点的子结点是否需要删除结点,而不能去判断当前这个结点是不是需要删除结点.
			2. 如果当前结点的左子结点不为空,并且左子结点 就是要删除结点,就将this.left = null; 并且就返回(结束递归删除)
			3. 如果当前结点的右子结点不为空,并且右子结点 就是要删除结点,就将this.right= null ;并且就返回(结束递归删除)
			4. 如果第2和第3步没有删除结点,那么我们就需要向左子树进行递归删除
			5.  如果第4步也没有删除结点,则应当向右子树进行递归删除.

		 */
		//2. 如果当前结点的左子结点不为空,并且左子结点 就是要删除结点,就将this.left = null; 并且就返回(结束递归删除)
		if(this.left != null && this.left.no == no) {
			this.left = null;
			return;
		}
		//3.如果当前结点的右子结点不为空,并且右子结点 就是要删除结点,就将this.right= null ;并且就返回(结束递归删除)
		if(this.right != null && this.right.no == no) {
			this.right = null;
			return;
		}
		//4.我们就需要向左子树进行递归删除
		if(this.left != null) {
			this.left.delNode(no);
		}
		//5.则应当向右子树进行递归删除
		if(this.right != null) {
			this.right.delNode(no);
		}
	}


//删除结点
	public void delNode(int no) {
		if(root != null) {
			//如果只有一个root结点, 这里立即判断root是不是就是要删除结点
			if(root.getNo() == no) {
				root = null;
			} else {
				//递归删除
				root.delNode(no);
			}
		}else{
			System.out.println("空树,不能删除~");
		}
	}

执行代码

 //测试一把删除结点

        System.out.println("删除前,前序遍历");
        binaryTree.preOrder(); //  1,2,3,5,4
        binaryTree.delNode(5);
        //binaryTree.delNode(3);
        System.out.println("删除后,前序遍历");
        binaryTree.preOrder(); // 1,2,3,4

执行结果

顺序存储二叉树

概念

基本说明 从数据存储来看,数组存储方式和树的存储方式可以相互转换,即数组可以转换成树,树也可以转换成数组,看右面的示意图。

要求: 右图的二叉树的结点,要求以数组 的方式来存放 arr : [1, 2, 3, 4, 5, 6, 6] 要求在遍历数组 arr时,仍然可以以 前序遍历,中序遍历和后序遍历的 方式完成结点的遍历

顺序存储二叉树的特点:

顺序二叉树通常只考虑完全二叉树 第n个元素的左子节点为 2 * n + 1 第n个元素的右子节点为 2 * n + 2 第n个元素的父节点为 (n-1) / 2

n : 表示二叉树中的第几个元素(按0开始编号 如图所示)

总结

顺序二叉树的概念,其实就是给出一个数组,这个数组可以根据上面满足的顺序二叉树的特点,构成(转化)一个完全二叉树。

顺序存储二叉树遍历实现

public class ArrBinaryTreeDemo {

	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
		//创建一个 ArrBinaryTree
		ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
		arrBinaryTree.preOrder(); // 1,2,4,5,3,6,7
	}

}

//编写一个ArrayBinaryTree, 实现顺序存储二叉树遍历

class ArrBinaryTree {
	private int[] arr;//存储数据结点的数组

	public ArrBinaryTree(int[] arr) {
		this.arr = arr;
	}
	
	//重载preOrder
	public void preOrder() {
		//数组的下标
		this.preOrder(0); 
	}
	
	//编写一个方法,完成顺序存储二叉树的前序遍历
	/**
	 * 
	 * @param index 数组的下标 
	 */
	public void preOrder(int index) {
		//如果数组为空,或者 arr.length = 0
		if(arr == null || arr.length == 0) {
			System.out.println("数组为空,不能按照二叉树的前序遍历");
		}
		//输出当前这个元素
		System.out.println(arr[index]); 
		//向左递归遍历
		if((index * 2 + 1) < arr.length) {
			preOrder(2 * index + 1 );
		}
		//向右递归遍历
		if((index * 2 + 2) < arr.length) {
			preOrder(2 * index + 2);
		}
	}
}

运行

待续。。