二叉树的创建
思路:使用递归进行创建。
- 使用前序遍历的方式创建
public static HeroNode createTree(HeroNode node){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入");
String next = scanner.next();
if (next.equals("#")){
node = null;
}else {
node = new HeroNode(0,next);
node.left = createTree(node.left);
node.right = createTree(node.right);
}
return node;
}
二叉树的复制
思路:使用递归进行复制
- 递归调用到顶部程序时,会向回走。返回的时候将根节点所需的左右节点带回,最后返回复制好的节点
public static HeroNode copyBinaryTree(HeroNode node){
if (node == null){
return null;
}
//创建一个临时节点,用于返回给上一层递归程序使用
HeroNode copyNode = new HeroNode(node.no, node.heroName);
//给根节点的右子节点赋值,调用copy方法,方法递归进行
copyNode.left = copyBinaryTree(node.left);
copyNode.right = copyBinaryTree(node.right);
return copyNode;
}
二叉树深度查询
思路:使用递归进行查询,
- 注意每次要加一。因为如果当前节点没有子节点。递归遍历到此此处会返回0。当回到本层时我们因该给他加上一,表示当前这一层。
public static int depthTree(HeroNode node){
if (node == null){
return 0;
}else {
int m = depthTree(node.left);
int n = depthTree(node.right);
//找到深度最大的那一个子节点,并返回
if (m > n){
return m+1;
}
return n+1;
}
}
二叉树节点数量
思路:使用递归进行统计
- 一旦当前节点没有子孩子,递归开始往回走。我们需要加一,因为需要加上根节点的数量(也就是当当前节点)。
public static int countNode(HeroNode node){
if (node == null){
return 0;
}
return countNode(node.left) + countNode(node.right) + 1;
}
二叉树叶子节点数量
- 思路:使用递归进行统计
- 跟节点统计方法大致相同。只不过当左右子节点都为空时在返回1,否则直接统计左右节点数量并返回给上一层递归的程序继续统计
public static int countLifeNode(HeroNode node){
//如果node为空则是空树,直接返回0
if (node == null){
return 0;
}
if (node.left == null && node.right == null){
return 1;
}else {
return countLifeNode(node.left)+countLifeNode(node.right);
}
}