二叉排序树
来源:互联网 发布:图文广告软件下载 编辑:程序博客网 时间:2024/06/04 19:55
二叉排序树的实现
代码如下:
package problem1;/** * @author Hutongling 二叉树排序--将一个整型数组中的元素存进二叉排序树中再查找元素; */class Node { int data; Node left; Node right; public Node() { } public Node(int value) { this.data = value; } public void setLeft(Node node) { this.left = node; } public void setRight(Node node) { this.right = node; } public Node getLeft() { return left; } public Node getRight() { return right; } public int getKey() { return data; } public void visitNode() { System.out.print(data + " "); }}public class CreateBinSortTree1 { public static void main(String[] args) { int[] array = { 19, 12, 3, 22, 6, 7, 21, 11, 43 }; Node root = new Node(array[0]); for (int i = 1; i < array.length; i++) { BinarySort(root, array[i]); } if (BinarySerch(root, 19)) { System.out.println("二叉树中存在此元素"); } else { System.out.println("二叉树中不存在该元素"); } System.out.print("中序遍历:"); inOrder(root); // 遍历指定的二叉树并输出--采用中序遍历法; System.out.print("\n先序遍历:"); priOrder(root); // 遍历指定的二叉树并输出--采用先序遍历法; System.out.print("\n后序遍历:"); postOrder(root); // 遍历指定的二叉树并输出--采用后序遍历法; } // 将指定的元素插入二叉排序树中 public static void BinarySort(Node root, int key) { int value = root.getKey(); // 判断该插入左子树还是右子树; if (key < value) { // 插入左子树 if (root.getLeft() == null) { Node node = new Node(key); root.setLeft(node); } else { BinarySort(root.getLeft(), key); } } else if (key > value) { // 插入右子树 if (root.getRight() == null) { Node node = new Node(key); root.setRight(node); } else { BinarySort(root.getRight(), key); } } } // 二叉树搜索树; public static boolean BinarySerch(Node root, int key) { if (root == null) { return false; } else if (root.getKey() == key) { return true; } else if (root.getKey() > key) { return BinarySerch(root.getLeft(), key); } else { return BinarySerch(root.getRight(), key); } } // 采用中序遍历法遍历一个二叉树 public static void inOrder(Node root) { if (root != null) { inOrder(root.getLeft()); root.visitNode(); inOrder(root.getRight()); } } // 采用先序遍历法遍历一个二叉树 public static void priOrder(Node root) { if (root != null) { root.visitNode(); inOrder(root.getLeft()); inOrder(root.getRight()); } } // 采用后序遍历法遍历一个二叉树 public static void postOrder(Node root) { if (root != null) { inOrder(root.getLeft()); inOrder(root.getRight()); root.visitNode(); } }}
代码结果如下:
二叉树中存在此元素
中序遍历:3 6 7 11 12 19 21 22 43
先序遍历:19 3 6 7 11 12 21 22 43
后序遍历:3 6 7 11 12 21 22 43 19
0 0
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 计蒜客——爬楼梯
- 51nod 1109 01 组成N倍数 bfs+同余剪枝
- iOS 离屏渲染的研究
- 扩展欧几里得算法
- 对线性回归、逻辑回归、各种回归的概念学习
- 二叉排序树
- 比较精确的计算农历节气的java源码
- JetsonTX1+Turtlebot+KinectV2配置小结
- 深搜与广搜以及例题
- java http工具类
- JSPatch热修复简单使用
- MaterialDesign——CardView
- ccf 最优配餐
- 编程练习(第四周)