面试的时候,往往面试官会强制你写出非递归的版本,网上关于非递归版本的介绍也有很多,这里我分享一个自己认为是比较好记的版本。
显然,我们需要用一个stack来模拟递归时的函数调用。对于三种遍历,我们都使用push当前节点->push左子树->pop左子树->push右子树->pop右子树的方式。但是cout时机会有所不同。
对于前序遍历来说,每次访问到一个节点就cout;
对于中序遍历来说,每次将右子节点进栈时,把当前节点cout;
对于后序遍历来说,每次pop的时候cout。
使用工具:循环 + 栈;
其实递归也是使用了内存中的栈。
思想如下:
对左节点依次做, 入栈
直到一个节点不存在左孩子时,出栈
出栈后,看其是否存在右孩子,
不存在,继续出栈
存在,则将其右孩子,入栈 …… 如此循环。
public static void perOrder(Node root) {
if(root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
Node A = stack.pop();
System.out.print(A.val + " ");
if(A.right != null) {
//将右子树先放入栈
//那木最后访问右子树
stack.push(A.right);
}
if(A.left != null) {
stack.push(A.left);
}
}
}
//中序遍历
public static void inOrder(Node root) {
if(root == null) {
return;
}
Stack<Node> stack = new Stack<>();
Node cur = root;
while(true) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
if(stack.empty()) {
break;
}
Node top = stack.pop();
System.out.print(top.val + " ");
cur = top.right;
}
}
//后序遍历
public static void postOrder(Node root) {
if(root == null) {
return;
}
Stack<Node> stack = new Stack<>();
Node cur = root;
Node prev = null;//来记录上一个被访问过的节点
while(true) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
if(stack.isEmpty()) {
break;
}
Node top = stack.peek();
if(top.right == null || top.right == prev) {
System.out.print(top.val + " ");
stack.pop();
prev = top;//保存被访问的节点
} else {
cur = top.right;
}
}
}