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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

java二叉树插入节点_[javaSE] 数据结构(二叉查找树-插入节点)

發(fā)布時間:2024/10/12 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java二叉树插入节点_[javaSE] 数据结构(二叉查找树-插入节点) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

public class BSTree>{private BSTNodemRoot;/*** 定義二叉樹

*

*@authortaoshihan

*@param

**/

public class BSTNode>{publicT key;publicBSTNode parent, left, right;publicBSTNode(T key, BSTNode parent, BSTNode left, BSTNode right) {this.key =key;this.parent =parent;this.left =left;this.right =right;

}

}public voidinsert(BSTree bsTree, BSTNode bstNode) {

BSTNode parent= null;

BSTNode x=bsTree.mRoot;//查找bstNode的插入位置,x的指針指對

while (x != null) {

parent= x;//把x的位置作為節(jié)點的父類

int flag =bstNode.key.compareTo(x.key);if (flag < 0) {

x=x.left;

}else{

x=x.right;

}

}//插入

bstNode.parent =parent;if(parent==null){

bsTree.mRoot=bstNode;

}else{int flag =bstNode.key.compareTo(parent.key);if (flag < 0) {

parent.left=bstNode;

}else{

parent.right=bstNode;

}

}

}/*** 插入根節(jié)點

*

*@paramkey*/

public voidinsert(T key) {

BSTNode z = new BSTNode(key, null, null, null);//如果新建結(jié)點失敗,則返回。

if (z != null)

insert(this, z);

}/** 打印"二叉查找樹"

*

* key -- 節(jié)點的鍵值

* direction -- 0,表示該節(jié)點是根節(jié)點;

* -1,表示該節(jié)點是它的父結(jié)點的左孩子;

* 1,表示該節(jié)點是它的父結(jié)點的右孩子。*/

private void print(BSTNode tree, T key, intdirection) {if(tree != null) {if(direction==0) //tree是根節(jié)點

System.out.printf("%2d is root\n", tree.key);else //tree是分支節(jié)點

System.out.printf("%2d is %2d's %6s child\n", tree.key, key, direction==1?"right" : "left");

print(tree.left, tree.key,-1);

print(tree.right,tree.key,1);

}

}public void print(BSTreetree) {if (tree.mRoot != null){

print(tree.mRoot, tree.mRoot.key,0);

}

}/***@paramargs*/

public static voidmain(String[] args) {

BSTree tree= newBSTree();

tree.insert(3);

tree.insert(1);

tree.insert(2);

tree.insert(5);

tree.insert(4);

tree.insert(6);

tree.print(tree);

}

}

總結(jié)

以上是生活随笔為你收集整理的java二叉树插入节点_[javaSE] 数据结构(二叉查找树-插入节点)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。