zoukankan      html  css  js  c++  java
  • 关于树的基本操作

    1.二叉树的比较常见的数据结构,下面用java实现简单的树的一下操作

    package tree;
    
    /**
     * @Author lizhilong
     * @create 2019/11/11 14:20
     * @desc
     */
    public class Tree<T> {
    
        T value;
    
        Tree<T> leftChild;
    
        Tree<T> rightChild;
    
        public Tree(T value) {
            this.value = value;
        }
    
        public Tree addLeft(T value) {
            Tree<T> left = new Tree<>(value);
            this.leftChild = left;
            return left;
        }
    
        public Tree addRight(T value) {
            Tree<T> right = new Tree<>(value);
            this.rightChild = right;
            return right;
        }
    
    
        public <T> int getNodeNum(Tree<T> tree) {
            if (tree == null) {
                return 0;
            }
            return (getNodeNum(tree.leftChild) + getNodeNum(tree.rightChild)+1);
        }
    
    
        public<T>  int getDeepNum(Tree<T> tree){
            if(tree == null){
                return 0;
            }
            int maxright = getDeepNum(tree.rightChild)+1;
            int maxleft = getDeepNum(tree.leftChild)+1;
            return  Math.max(maxleft,maxright);
    
        }
    
    
        /**
         * 前序遍历
         * 根->左->右
         * @param tree
         */
        public  void preVisit(Tree tree){
            if(tree==null){
                return;
            }
            print(tree);
            preVisit(tree.leftChild);
            preVisit(tree.rightChild);
        }
    
        /**
         * 中序遍历
         * 左->根->右
         * @param tree
         */
        public void midVist(Tree tree){
            if(tree == null){
                return;
            }
            midVist(tree.leftChild);
            print(tree);
            midVist(tree.rightChild);
        }
    
        /**
         * 后续遍历
         * 左->右->根
         * @param tree
         */
        public void  afterVisit(Tree tree){
            if(tree == null){
                return;
            }
            afterVisit(tree.leftChild);
            afterVisit(tree.rightChild);
            print(tree);
        }
    
    
        public void print(Tree tree){
            System.out.print(tree.value+"   ");
        }
    
    }
  • 相关阅读:
    序列化器:serializers(django-rest-framework)
    数据库模型:models(Django)
    AtCoder Beginner Contest 213【A
    Codeforces Round #736 (Div. 2)【ABCD】
    AtCoder Beginner Contest 212【A
    Codeforces Round #732 (Div. 2)【ABCD】
    VS201X windows下编译提示缺少ucrtbased.dll文件
    Locust1.6 从入门到实战
    如何理解Windows认证流程
    HTB::Forest
  • 原文地址:https://www.cnblogs.com/li-zhi-long/p/11842635.html
Copyright © 2011-2022 走看看