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+"   ");
        }
    
    }
  • 相关阅读:
    iOS
    UI基本视图控制
    堆和栈的区别 ?
    单例模式
    Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?
    id
    协议
    分类(类别)
    #import和#include以及@class三者的区别?
    内存管理
  • 原文地址:https://www.cnblogs.com/li-zhi-long/p/11842635.html
Copyright © 2011-2022 走看看