public class MyTree {
//结点类
static class TreeNode {
public TreeNode left;
public TreeNode right;
public String val;
public TreeNode() {
}
public TreeNode(String val) {
this.val = val;
}
}
//前序遍历
private void preOrder(TreeNode root){
if(root == null){
return;
}
System.out.print(root.val+" ");
preOrder(root.left);
preOrder(root.right);
}
//中序遍历
private void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
System.out.print(root.val+" ");
inOrder(root.right);
}
//后序遍历
private void postOrder(TreeNode root){
if(root == null){
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val+" ");
}
//计算总结点个数
public int count = 0;
//一、计数器写法
public void size(TreeNode root) {
if(root == null){
return;
}
count++;
size(root.left);
size(root.right);
}
//二、节点数 = 左子树 + 右子树 + 根节点
public int size2(TreeNode root) {
if(root == null){
return 0;
}
return size2(root.left) + size2(root.right) + 1;
}
//计算叶子结点个数
public int count2;
//一、计数器写法
public void getLeafNodeCount(TreeNode root){
if (root == null){
return;
}
if(root.left == null && root.right == null){
count2++;
}
getLeafNodeCount(root.left);
getLeafNodeCount(root.right);
}
//二、叶子结点 = 左子树叶子 + 右子树叶子
public int getLeafNodeCount2(TreeNode root){
if (root == null){
return 0;
}
if(root.left == null && root.right == null){
return 1;
}
return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
}
//求某一层的结点个数
//整棵树的第k层 = 左子树第k-1层 + 右子树第k-1层
public int getLevelNodeCount(TreeNode root,int k){
if(root == null){
return 0;
}
if (k == 1){
return 1;
}
return getLevelNodeCount(root.left,k-1) + getLevelNodeCount(root.right,k-1);
}
//二叉树的高度
public int getMaxHeight(TreeNode root){
if (root == null){
return 0;
}
int leftHeight = getMaxHeight(root.left);
int rightHeight = getMaxHeight(root.right);
return Math.max(leftHeight,rightHeight)+1;
}
//寻找结点是否存在
public TreeNode find(TreeNode root,String val){
if (root == null){
return null;
}
if(root.val.equals(val)){
return root;
}
TreeNode treeNode = find(root.left,val);
if(treeNode != null){
return treeNode;
}
return find(root.right,val);
}
}
测试类:
java复制代码
public static void main(String[] args) {
TreeNode A = new TreeNode("A");
TreeNode B = new TreeNode("B");
TreeNode C = new TreeNode("C");
TreeNode D = new TreeNode("D");
TreeNode E = new TreeNode("E");
TreeNode F = new TreeNode("F");
TreeNode G = new TreeNode("G");
TreeNode H = new TreeNode("H");
//进行连接
A.left = B;
A.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
E.right = H;
// 此时的结构为:
// A
// / \
// B C
// / \ / \
// D E F G
// \
// H
}