二叉树
二叉树结点的构建
< pre>
class BinNode {
public int data;
public int height;
public BinNode parent;
public BinNode left;
public BinNode right;
public BinNode ( int data) {
super ( ) ;
this . data = data;
this . height = 0 ;
this . parent = null;
this . left = null;
this . right = null;
}
public BinNode insertLeftNode ( int data) {
if ( this . left == null) {
BinNode leftNode = new BinNode ( data) ;
this . left = leftNode;
leftNode. parent = this ;
} else {
System. out. println ( "当前节点的左节点不为空" ) ;
}
return this . left;
}
public BinNode insertRightNode ( int data) {
if ( this . right == null) {
BinNode rightNode = new BinNode ( data) ;
this . left = rightNode;
rightNode. parent = this ;
} else {
System. out. println ( "当前节点的右节点不为空" ) ;
}
return this . right;
}
public int size ( ) {
int s = 1 ;
if ( this . left != null) {
s += this . left. size ( ) ;
}
if ( this . right != null) {
s += this . right. size ( ) ;
}
return s;
}
}
< / pre>
二叉树的构建及其相关接口
< pre>
class BinTree {
public BinNode root;
public int treeSize;
public BinTree ( ) {
this . root = null;
}
public BinTree ( BinNode node) {
this . root = node;
}
public boolean isEmpty ( ) {
return this . root == null ? true : false ;
}
public int updateHeight ( BinNode node) {
int subHeight = node. left. height > node. right. height? node. left. height : node. right. height;
node. height = 1 + subHeight;
return node. height;
}
public void updateHeightOver ( BinNode node) {
while ( node. parent != null) {
node. height = updateHeight ( node) ;
node = node. parent;
}
}
public BinNode insertLeftNode ( BinNode x, int data) {
BinNode xLeft = x. insertLeftNode ( data) ;
updateHeightOver ( x) ;
return xLeft;
}
public BinNode insertRightNode ( BinNode x, int data) {
BinNode xRight = x. insertRightNode ( data) ;
updateHeightOver ( x) ;
return xRight;
}
public BinNode insertRightTree ( BinNode x, BinTree tree) {
if ( x. right == null) {
x. right = tree. root;
} else {
System. out. println ( "无法插入" ) ;
}
updateHeightOver ( x) ;
return x. right;
}
public BinNode insertLeftTree ( BinNode x, BinTree tree) {
if ( x. left == null) {
x. left = tree. root;
} else {
System. out. println ( "无法插入" ) ;
}
updateHeightOver ( x) ;
return x. left;
}
public void removeLeftTree ( BinNode x) {
x. left = null;
updateHeightOver ( x) ;
}
public void removeRightTree ( BinNode x) {
x. right = null;
updateHeightOver ( x) ;
}
}
< / pre>