网上关于二叉树的遍历很多,不一定都全,希望我这个可以全一些。
Node
private class BinaryNode<Any extends Comparable<Any>> {
public Any data;
public BinaryNode<Any> left;
public BinaryNode<Any> right;
public BinaryNode<Any> parent;
public BinaryNode(Any data, BinaryNode<Any> left, BinaryNode<Any> right, BinaryNode<Any> parent) {
this.data = data;
this.left = left;
this.right = right;
this.parent = parent;
}
}
复制代码
前序遍历递归法
顺序是根左右,没什么好记的
private void preOrder(BinaryNode<Any> root) {
if (root == null)
return;
System.out.println(root.data);
preOrder(root.left);
preOrder(root.right);
}
复制代码
前序遍历迭代法
用一个栈来实现,压入根节点,再弹出,判断弹出之节点的右孩子以及左孩子(顺序不能倒)是否为空,再压栈
private void preOrder(BinaryNode<Any> root) {
if (root == null)
return;
Stack<BinaryNode<Any>> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
BinaryNode<Any> cur = stack.pop();
System.out.println(cur.data);
if (cur.right != null)
stack.push(cur.right);
if (cur.left != null)
stack.push(cur.left);
}
}
复制代码
中序遍历递归法
顺序左根右,仅此而已
private void inOrder(BinaryNode<Any> root) {
if (root == null)
return;
inOrder(root.left);
System.out.println(root.data);
inOrder(root.right);
}
复制代码
中序遍历迭代法
关键记住中序是一路向左的,还是用一个栈来实现
private void inOrder(BinaryNode<Any> root) {
if (root == null)
return;
Stack<BinaryNode<Any>> stack = new Stack<>();
BinaryNode<Any> cur = root;
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
cur = stack.pop();
System.out.println(cur.data);
cur = cur.right;
}
}
}
复制代码
后序遍历递归法
顺序左右根
private void postOrder(BinaryNode<Any> root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.println(root.data);
}
复制代码
后序遍历迭代法
关键点,两个栈实现一个队列
private void postOrder2(BinaryNode<Any> root) {
if (root == null)
return;
Stack<BinaryNode<Any>> s = new Stack<>();
Stack<BinaryNode<Any>> output = new Stack<>();
s.push(root);
while (!s.isEmpty()) {
BinaryNode cur = s.pop();
output.push(cur);
if (cur.left != null)
s.push(cur.left);
if (cur.right != null)
s.push(cur.right);
}
while (!output.isEmpty()) {
System.out.println(output.pop().data);
}
}
复制代码
深度遍历迭代法
private void DFS(BinaryNode<Any> root) {
if (root == null)
return;
Stack<BinaryNode<Any>> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
BinaryNode<Any> cur = stack.pop();
System.out.println(cur.data);
if (cur.right != null)
stack.push(cur.right);
if (cur.left != null)
stack.push(cur.left);
}
}
复制代码
广度遍历迭代法
private void BFS(BinaryNode<Any> root) {
if (root == null)
return;
Queue<BinaryNode<Any>> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
BinaryNode<Any> cur = queue.poll();
System.out.print(cur.data + " ");
if (cur.left != null)
queue.offer(cur.left);
if (cur.right != null)
queue.offer(cur.right);
}
}
复制代码