Java代码实现在一颗三叉链表表示的二叉树中返回指定结点的父母结点,并输出运行结果
时间: 2024-03-14 17:43:38 浏览: 66
以下是Java代码实现:
```java
public class TriTreeNode {
int data;
TriTreeNode left;
TriTreeNode right;
TriTreeNode parent;
// constructor
public TriTreeNode(int data) {
this.data = data;
this.left = null;
this.right = null;
this.parent = null;
}
}
public class TriTree {
TriTreeNode root;
// constructor
public TriTree() {
root = null;
}
// method to find the parent node of a given node
public TriTreeNode findParent(TriTreeNode node) {
if (node == null || node == root) {
return null;
} else {
return node.parent;
}
}
// main method to test the findParent method
public static void main(String[] args) {
TriTree tree = new TriTree();
tree.root = new TriTreeNode(1);
tree.root.left = new TriTreeNode(2);
tree.root.right = new TriTreeNode(3);
tree.root.left.parent = tree.root;
tree.root.right.parent = tree.root;
tree.root.left.left = new TriTreeNode(4);
tree.root.left.right = new TriTreeNode(5);
tree.root.left.left.parent = tree.root.left;
tree.root.left.right.parent = tree.root.left;
tree.root.right.left = new TriTreeNode(6);
tree.root.right.right = new TriTreeNode(7);
tree.root.right.left.parent = tree.root.right;
tree.root.right.right.parent = tree.root.right;
TriTreeNode node = tree.root.left.right;
TriTreeNode parent = tree.findParent(node);
if (parent == null) {
System.out.println("Node " + node.data + " has no parent.");
} else {
System.out.println("Parent of node " + node.data + " is " + parent.data);
}
}
}
```
输出结果为:
```
Parent of node 5 is 2
```
在main方法中,我们构造了一颗三叉链表表示的二叉树,并找到其中一个结点的父结点并输出。运行结果表明,结点5的父结点是2。
阅读全文