Java代码实现构造一颗三叉链表表示的二叉树,实现创建方法体在二叉树中查找一个结点
时间: 2024-01-23 07:15:11 浏览: 81
二叉树的java实现
以下是Java代码实现构造一颗三叉链表表示的二叉树,以及在二叉树中查找一个结点的方法:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode parent;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
this.parent = null;
}
}
class ThreeLinkBinaryTree {
private TreeNode root;
public ThreeLinkBinaryTree() {
this.root = null;
}
public void createTree(int[] arr) {
for (int i = 0; i < arr.length; i++) {
insert(arr[i]);
}
}
private void insert(int val) {
TreeNode newNode = new TreeNode(val);
if (root == null) {
root = newNode;
} else {
TreeNode current = root;
TreeNode parent;
while (true) {
parent = current;
if (val < current.val) {
current = current.left;
if (current == null) {
parent.left = newNode;
newNode.parent = parent;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
newNode.parent = parent;
return;
}
}
}
}
}
public TreeNode findNode(int val) {
TreeNode current = root;
while (current != null && current.val != val) {
if (val < current.val) {
current = current.left;
} else {
current = current.right;
}
}
return current;
}
}
```
使用示例:
```java
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 1, 4, 6, 9 };
ThreeLinkBinaryTree tree = new ThreeLinkBinaryTree();
tree.createTree(arr);
TreeNode node = tree.findNode(4);
if (node != null) {
System.out.println("找到了节点:" + node.val);
} else {
System.out.println("未找到节点");
}
}
```
阅读全文