日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java 实现二叉树操作

發布時間:2025/4/16 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 实现二叉树操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

java實現二叉樹的創建、先序遍歷、中序遍歷、后序遍歷及二叉樹的深度??


public class Tree {

?private int data;// 數據節點
?private Tree left;// 左子樹
?private Tree right;// 右子樹

?public Tree(int data) {
??this.data = data;
??this.left = null;
??this.right = null;
?}

?/**
? * 創建二叉樹,返回根結點
? *?
? * @param input
? * @return
? */
?public static Tree createTree(int[] input) {
??Tree root = null;
??Tree temp = null;
??for (int i = 0; i < input.length; i++) {
???// 創建根節點
???if (root == null) {
????root = temp = new Tree(input[i]);
???} else {
????// 回到根結點
????temp = root;
????// 添加節點
????while (temp.data != input[i]) {
?????if (input[i] <= temp.data) {
??????if (temp.left != null) {
???????temp = temp.left;
??????} else {
???????temp.left = new Tree(input[i]);
??????}
?????} else {
??????if (temp.right != null) {
???????temp = temp.right;
??????} else {
???????temp.right = new Tree(input[i]);
??????}
?????}
????}
???}
??}
??return root;
?}

?/**
? * 前序遍歷
? *?
? * @param tree
? */
?public static void preOrder(Tree tree) {
??if (tree != null) {
???System.out.print(tree.data + " ");
???preOrder(tree.left);
???preOrder(tree.right);
??}
?}

?/**
? * 中序遍歷
? *?
? * @param tree
? */
?public static void midOrder(Tree tree) {
??if (tree != null) {
???midOrder(tree.left);
???System.out.print(tree.data + " ");
???midOrder(tree.right);
??}
?}

?/**
? * 后序遍歷
? *?
? * @param tree
? */
?public static void posOrder(Tree tree) {
??if (tree != null) {
???posOrder(tree.left);
???posOrder(tree.right);
???System.out.print(tree.data + " ");
??}
?}
?
?/**
? * 求二叉樹的深度
? *?
? * @param tree
? */
?public static int length(Tree tree){
??int depth1;
??int depth2;
??if(tree == null) return 0;
??//左子樹的深度
??depth1 = length(tree.left);
??//右子樹的深度
??depth2 = length(tree.right);
??if(depth1>depth2)
???return depth1+1;
??else
???return depth2+1;
?}


?/**
? * @param args
? */
?public static void main(String[] args) {
??int[] input = { 4, 2, 6, 1, 3, 5, 7,8,10 };
??Tree tree = createTree(input);
??System.out.print("前序遍歷:");
??preOrder(tree);
??System.out.print("\n二叉樹深度為:"+length(tree));
??
??System.out.print("\n中序遍歷:");
??midOrder(tree);
??System.out.print("\n后序遍歷:");
??posOrder(tree);
?}
}

總結

以上是生活随笔為你收集整理的java 实现二叉树操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。