二叉排序树中序遍历
时间: 2023-12-16 13:28:10 浏览: 116
二叉排序树的中序遍历是按照左子树、根节点、右子树的顺序遍历整棵树。具体实现可以使用递归或者非递归方式。以下是两种实现方式:
1. 递归方式
```java
public void inOrder(TreeNode treeNode) {
if (treeNode == null) {
return;
}
inOrder(treeNode.leftChild);
System.out.print(treeNode.data + " ");
inOrder(treeNode.rightChild);
}
```
2. 非递归方式
```java
public void inOrder(TreeNode treeNode) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = treeNode;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.leftChild;
}
current = stack.pop();
System.out.print(current.data + " ");
current = current.rightChild;
}
}
```
阅读全文