Java代码实现二叉树后根次序遍历的非递归算法
时间: 2023-07-25 14:34:46 浏览: 91
好的,以下是Java代码实现二叉树后根次序遍历的非递归算法:
```java
import java.util.Stack;
class Node {
int val;
Node left, right;
public Node(int val) {
this.val = val;
left = right = null;
}
}
public class BinaryTree {
Node root;
public void postOrderTraversal() {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
Node node = root;
Node lastVisited = null;
while (!stack.isEmpty() || node != null) {
if (node != null) {
stack.push(node);
node = node.left;
} else {
Node peekNode = stack.peek();
if (peekNode.right != null && lastVisited != peekNode.right) {
node = peekNode.right;
} else {
lastVisited = stack.pop();
System.out.print(lastVisited.val + " ");
}
}
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
System.out.println("Postorder traversal of binary tree is :");
tree.postOrderTraversal();
}
}
```
这里使用了一个栈 `stack` 和一个指针 `node`,首先将根节点赋值给 `node`,然后进入循环,当 `stack` 不为空或者 `node` 不为 null 时循环继续。对于每个节点,首先将其左子节点入栈,然后将指针 `node` 指向左子节点,直到最左边的子节点。当一个节点的左子节点为空时,从栈中弹出该节点并打印,然后将指针 `node` 指向该节点的右子节点。如果该节点的右子节点为空或者已经被访问过(即 `lastVisited == peekNode.right`),则说明该节点的右子树已经被遍历过了,可以将该节点弹出并打印。
上述代码的输出结果为:
```
Postorder traversal of binary tree is :
4 5 2 6 7 3 1
```
阅读全文