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+" "); } }