定义二叉树的结点类型
public class BinTree {
public int root;
public BinTree left;
public BinTree right;
public BinTree ( int root, BinTree left, BinTree right) {
this . root = root;
this . left = left;
this . right = right;
}
}
二叉树的随机创建
public static void createRandomBinTree ( BinTree binTree) {
int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ;
BinTree node = binTree;
for ( int i = 0 ; i < arr. length; i++ ) {
if ( Math. random ( ) > 0.5 ) {
node. left = new BinTree ( arr[ i] , null, null) ;
node. right = null;
node = node. left;
} else {
node. left = null;
node. right = new BinTree ( arr[ i] , null, null) ;
node = node. right;
}
}
}
完全二叉树的创建
public static void createBinTree ( BinTree binTree) {
int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ;
Queue< BinTree> queue = new LinkedList < > ( ) ;
queue. add ( binTree) ;
for ( int i= 0 ; i< arr. length; i++ ) {
if ( ! queue. isEmpty ( ) ) {
BinTree node = queue. poll ( ) ;
node. left = new BinTree ( arr[ i] , null, null) ;
if ( i< arr. length- 1 ) {
node. right = new BinTree ( arr[ ++ i] , null, null) ;
}
queue. add ( node. left) ;
queue. add ( node. right) ;
}
}
}
二叉树的先、中、后序(递归)遍历
public static void preOrder ( BinTree node) {
System. out. print ( node. root+ " " ) ;
if ( node. left!= null) {
preOrder ( node. left) ;
}
if ( node. right!= null) {
preOrder ( node. right) ;
}
}
public static void midOrder ( BinTree node) {
if ( node. left!= null) {
midOrder ( node. left) ;
}
System. out. print ( node. root+ " " ) ;
if ( node. right!= null) {
midOrder ( node. right) ;
}
}
public static void lastOrder ( BinTree node) {
if ( node. left!= null) {
lastOrder ( node. left) ;
}
if ( node. right!= null) {
lastOrder ( node. right) ;
}
System. out. print ( node. root+ " " ) ;
}
二叉树的层次遍历+非递归求深度
public static void levelOrder ( BinTree root) {
Queue< BinTree> queue = new LinkedList < > ( ) ;
queue. add ( root) ;
System. out. print ( root. root+ " " ) ;
int deep = 0 ;
while ( ! queue. isEmpty ( ) ) {
int size = queue. size ( ) ;
while ( size> 0 ) {
BinTree node = queue. poll ( ) ;
if ( node. left!= null) {
System. out. print ( node. left. root+ " " ) ;
queue. add ( node. left) ;
}
if ( node. right!= null) {
System. out. print ( node. right. root+ " " ) ;
queue. add ( node. right) ;
}
-- size;
}
++ deep;
}
System. out. println ( "\n二叉树的深度为:" + deep) ;
}
二叉树的深度
public static int deep ( BinTree root) {
if ( root == null)
return 0 ;
int l = deep ( root. left) ;
int r = deep ( root. right) ;
return l> r? 1 + 1 : r+ 1 ;
}
二叉树的翻转/镜像
public static TreeNode mirrorTree ( TreeNode root) {
if ( root == null || ( root. left == null && root. right == null) )
return root;
TreeNode tmp = root. left;
root. left = root. right;
root. right = tmp;
if ( root. left!= null) {
mirrorTree ( root. left) ;
}
if ( root. right!= null) {
mirrorTree ( root. right) ;
}
return root;
}
操作持续更新中…