Java代码实现构造一颗三叉链表表示的二叉树,实现输入叶子结点、 求二叉树中叶子结点个数、插入结点
时间: 2024-01-23 10:15:01 浏览: 81
基于链表实现二叉树(java算法源码)
以下是Java代码实现构造一颗三叉链表表示的二叉树,实现输入叶子结点、求二叉树中叶子结点个数、插入结点的示例代码:
```java
class TreeNode {
int data;
TreeNode leftChild;
TreeNode rightChild;
TreeNode parent;
public TreeNode(int data) {
this.data = data;
this.leftChild = null;
this.rightChild = null;
this.parent = null;
}
}
class ThreeLinkBinaryTree {
TreeNode root;
public ThreeLinkBinaryTree(int data) {
root = new TreeNode(data);
}
// 插入节点
public void insert(TreeNode parent, boolean isLeft, int data) {
TreeNode newNode = new TreeNode(data);
if (isLeft) {
parent.leftChild = newNode;
} else {
parent.rightChild = newNode;
}
newNode.parent = parent;
}
// 输入叶子节点
public void inputLeafNodes(TreeNode node, Scanner scanner) {
System.out.println("请输入节点 " + node.data + " 的左子节点:");
int leftData = scanner.nextInt();
if (leftData != -1) {
TreeNode leftChild = new TreeNode(leftData);
node.leftChild = leftChild;
leftChild.parent = node;
inputLeafNodes(leftChild, scanner);
}
System.out.println("请输入节点 " + node.data + " 的中间子节点:");
int midData = scanner.nextInt();
if (midData != -1) {
TreeNode midChild = new TreeNode(midData);
node.rightChild = midChild;
midChild.parent = node;
inputLeafNodes(midChild, scanner);
}
System.out.println("请输入节点 " + node.data + " 的右子节点:");
int rightData = scanner.nextInt();
if (rightData != -1) {
TreeNode rightChild = new TreeNode(rightData);
node.rightChild.rightChild = rightChild;
rightChild.parent = node;
inputLeafNodes(rightChild, scanner);
}
}
// 求二叉树中叶子节点个数
public int getLeafNodeCount(TreeNode node) {
if (node == null) {
return 0;
}
if (node.leftChild == null && node.rightChild == null) {
return 1;
} else {
return getLeafNodeCount(node.leftChild) + getLeafNodeCount(node.rightChild);
}
}
}
```
使用示例:
```java
Scanner scanner = new Scanner(System.in);
System.out.println("请输入根节点:");
int rootData = scanner.nextInt();
ThreeLinkBinaryTree tree = new ThreeLinkBinaryTree(rootData);
tree.inputLeafNodes(tree.root, scanner);
System.out.println("叶子节点个数为:" + tree.getLeafNodeCount(tree.root));
System.out.println("请输入要插入的节点:");
int data = scanner.nextInt();
tree.insert(tree.root, true, data);
System.out.println("叶子节点个数为:" + tree.getLeafNodeCount(tree.root));
```
注意:上述代码中的 `inputLeafNodes` 方法实现了输入三叉链表表示的二叉树的所有节点,其中输入 `-1` 表示该节点为空。
阅读全文