java二叉树插入节点_[javaSE] 数据结构(二叉查找树-插入节点)
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的指針指對(duì)
while (x != null) {
parent= x;//把x的位置作為節(jié)點(diǎn)的父類
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é)點(diǎn)
*
*@paramkey*/
public voidinsert(T key) {
BSTNode z = new BSTNode(key, null, null, null);//如果新建結(jié)點(diǎn)失敗,則返回。
if (z != null)
insert(this, z);
}/** 打印"二叉查找樹"
*
* key -- 節(jié)點(diǎn)的鍵值
* direction -- 0,表示該節(jié)點(diǎn)是根節(jié)點(diǎn);
* -1,表示該節(jié)點(diǎn)是它的父結(jié)點(diǎn)的左孩子;
* 1,表示該節(jié)點(diǎn)是它的父結(jié)點(diǎn)的右孩子。*/
private void print(BSTNode tree, T key, intdirection) {if(tree != null) {if(direction==0) //tree是根節(jié)點(diǎn)
System.out.printf("%2d is root\n", tree.key);else //tree是分支節(jié)點(diǎn)
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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu11.04 安装sun-ja
- 下一篇: java分装_Java ——Number