用java做,实现输出二叉树先序、中序和后序遍历序列中第k个数据元素的操作,要求带泛型
时间: 2024-10-24 20:13:57 浏览: 31
在Java中,我们可以使用递归或栈来分别实现二叉树的先序(Preorder)、中序(Inorder)和后序(Postorder)遍历。这里我们先创建一个泛型的二叉树节点类`TreeNode<T>`,然后提供三个遍历并获取第k个元素的方法:
```java
import java.util.Stack;
class TreeNode<T> {
T data;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(T item) {
this.data = item;
this.left = null;
this.right = null;
}
}
public class BinaryTreeTraversal {
public static class NodeIterator<T> implements Iterator<T> {
private TreeNode<T> current;
private Stack<TreeNode<T>> stack;
private int count;
public NodeIterator(TreeNode<T> root) {
current = root;
stack = new Stack<>();
if (current != null) {
push(current);
}
count = 1;
}
@Override
public boolean hasNext() {
return !stack.isEmpty() || current != null;
}
@Override
public T next() {
if (count > 1) {
count--;
return current.data;
}
while (hasNext()) {
T data = current.data;
current = current.left == null ? current.right : current.left;
if (current != null) {
stack.push(current);
}
}
current = stack.pop();
count = 2;
return current.data;
}
}
public static void main(String[] args) {
// 创建一个二叉树实例并插入数据...
TreeNode<Integer> root = ...;
// 使用NodeIterator获取先序遍历的第k个元素
NodeIterator<Integer> preorderKth = new NodeIterator<>(root);
System.out.println("先序遍历第" + k + "个元素: " + preorderKth.next());
// 同样的方式可以获取中序和后序遍历的第k个元素
// NodeIterator inorderKth = new NodeIterator<>(root);
// System.out.println("中序遍历第" + k + "个元素: " + inorderKth.next());
// NodeIterator postorderKth = new NodeIterator<>(root);
// System.out.println("后序遍历第" + k + "个元素: " + postorderKth.next());
}
}
```
在这个例子中,我们首先创建了一个`NodeIterator`类作为迭代器,它内部维护了当前访问的节点和一个栈来辅助中序遍历。先序遍历直接从根开始,所以不需要额外的数据结构。中序遍历需要借助栈来保存待访问的左子树,后序遍历则更复杂,需要两个栈。
阅读全文