首先,构建一棵树。
static class Node {
public char val;
public Node left;
public Node right;
public Node ( char val) {
this . val = val;
}
@Override
public String toString ( ) {
return "Node{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}' ;
}
}
static Node build ( ) {
Node A = new Node ( 'A' ) ;
Node B = new Node ( 'B' ) ;
Node C = new Node ( 'C' ) ;
Node D = new Node ( 'D' ) ;
Node E = new Node ( 'E' ) ;
Node F = new Node ( 'F' ) ;
Node G = new Node ( 'G' ) ;
A. left = B;
A. right = C;
B. left = D;
B. right = E;
E. left = G;
C. right = F;
return A;
}
计算节点个数
public static int size ( Node root) {
if ( root == null) {
return 0 ;
}
return 1 + size ( root. left) + size ( root. right) ;
}
计算叶子节点
public static int leafSize ( Node root) {
if ( root == null) {
return 0 ;
}
if ( root. left == null && root. right == null) {
return 1 ;
}
return leafSize ( root. left) + leafSize ( root. right) ;
}
计算第 k 层节点个数
public static int kLevelSize ( Node root, int k) {
if ( root == null || k < 1 ) {
return 0 ;
}
if ( k == 1 ) {
return 1 ;
}
return kLevelSize ( root. left, k- 1 ) + kLevelSize ( root. right, k- 1 ) ;
}
查找 val 所在节点
public static Node find ( Node root, char toFind) {
if ( root == null) {
return null;
}
if ( root. val == toFind) {
return root;
}
Node result = find ( root. left, toFind) ;
if ( result != null) {
return result;
}
return find ( root. right, toFind) ;
}
检验两个二叉树是否相同
static Node p ( ) {
Node num1 = new Node ( 1 ) ;
Node num2 = new Node ( 2 ) ;
num1. left = num2;
return num1;
}
static Node q ( ) {
Node num1 = new Node ( 1 ) ;
Node num2 = new Node ( 2 ) ;
num1. right = num2;
return num1;
}
public static boolean isSameTree ( Node p, Node q) {
if ( p == null && q == null) {
return true ;
}
if ( p != null && q != null && p. val == q. val) {
return isSameTree ( p. left, q. left) && isSameTree ( p. right, q. right) ;
} else {
return false ;
}
}
主函数调用
public static void main ( String[ ] args) {
Node root = build ( ) ;
System. out. println ( size ( root) ) ;
System. out. println ( leafSize ( root) ) ;
System. out. println ( kLevelSize ( root, 3 ) ) ;
Node result = find ( root, 'G' ) ;
System. out. println ( result) ;
Node result1 = find ( root, 'C' ) ;
System. out. println ( result1) ;
boolean ret = isSameTree ( p ( ) , q ( ) ) ;
System. out. println ( ret) ;
}