public class Main {
static int num=0;
public static void main(String[] args) {
int[] arr = {4, 1, 8, 2, 3, 7, 6, 5};
Node root = new Node(arr[0]);
for(int i=1; i<arr.length; i++) {
root.store(new Node(arr[i]));
}
root.pre();
System.out.println();
root.mid();
System.out.println();
root.after();
System.out.println();
System.out.println(root.find(0));
System.out.println();
System.out.println(root.find(3));
System.out.println();
leaf(root);
System.out.println();
outleaf(root);
System.out.println(num);
System.out.println(depth(root));
System.out.println(leftchild(5, root));
System.out.println(rightchild(5, root));
System.out.println(parent(3, root));
}
static void leaf(Node n) {
if(n != null) {
if(n.left == null && n.right == null) {
System.out.print(n.data + " ");
} else {
leaf(n.left);
leaf(n.right);
}
}
}
static void outleaf(Node n) {
if(n != null) {
if(n.left == null && n.right == null) {
num++;
} else {
outleaf(n.left);
outleaf(n.right);
}
}
}
static int depth(Node n) {
if(n == null) {
return 0;
} else {
int h1 = depth(n.left);
int h2 = depth(n.right);
int max = h1 > h2 ? h1 : h2;
return max + 1;
}
}
static boolean parent(int d, Node n) {
if((n.left != null && n.left.data == d) || (n.right != null && n.right.data == d) ) {
System.out.println(n.data);
return true;
} else if(n.left != null && parent(d, n.left)) {
return true;
} else if(n.right != null && parent(d, n.right)) {
return true;
} else {
return false;
}
}
static boolean leftchild(int d, Node n) {
if(n.data == d) {
if(n.left == null) {
return false;
} else {
System.out.println(n.left.data);
return true;
}
} else if(n.left != null && leftchild(d, n.left)) {
return true;
} else if(n.right != null && leftchild(d, n.right)) {
return true;
} else {
return false;
}
}
static boolean rightchild(int d, Node n) {
if(n.data == d) {
if(n.right == null) {
return false;
} else {
System.out.println(n.right.data);
return true;
}
} else if(n.left != null && rightchild(d, n.left)) {
return true;
} else if(n.right != null && rightchild(d, n.right)) {
return true;
} else {
return false;
}
}
}
class Node {
int data;
Node left;
Node right;
Node(){}
Node(int d) {
data = d;
}
void store(Node n) {
if(n.data < data) {
if(left == null) {
left = n;
} else {
left.store(n);
}
} else {
if(right == null) {
right = n;
} else {
right.store(n);
}
}
}
void pre() {
System.out.print(data+" ");
if(left != null) {
left.pre();
}
if(right != null) {
right.pre();
}
}
void mid() {
if(left != null) {
left.mid();
}
System.out.print(data+" ");
if(right != null) {
right.mid();
}
}
void after() {
if(left != null) {
left.after();
}
if(right != null) {
right.after();
}
System.out.print(data+" ");
}
boolean find(int d) {
System.out.print(data+" ");
if(d == data) {
return true;
}
if(left != null && left.find(d)) {
return true;
}else if(right != null && right.find(d)) {
return true ;
} else {
return false;
}
}
}
二叉树常见运算
最新推荐文章于 2021-06-18 20:54:11 发布