递归的思路非常简单,只需调整打印位置即可
非递归思路
(1)前序遍历
使用一个栈,先将根节点放入栈,然后出栈,然后分别按照 右节点、左节点的顺序放入栈,继续循环出栈
(2)中序遍历
使用一个栈,先不断的遍历最左侧的节点放入栈,如果左边为null了则出栈null的父节点,然后将父节点右子树做相同的操作,最后直到栈为空
(3)后序遍历
使用两个栈,先将根节点入栈,然后出栈并放入栈2,然后放入左节点,右节点然后再出栈放入栈2,最后将栈2出栈打印即可
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class TreeToSequence {
public int[][] convert(TreeNode root) {
List<Integer> preResult = new ArrayList<>();
List<Integer> midResult = new ArrayList<>();
List<Integer> afterResult = new ArrayList<>();
prePrint(preResult, root);
midPrint(midResult, root);
afterPrint(afterResult, root);
int[][] result = new int[3][preResult.size()];
for (int i=0; i< preResult.size(); i++) {
result[0][i] = preResult.get(i);
}
for (int i=0; i< midResult.size(); i++) {
result[1][i] = midResult.get(i);
}
for (int i=0; i< afterResult.size(); i++) {
result[2][i] = afterResult.get(i);
}
return result;
}
private void prePrint(List<Integer> preResult,TreeNode node) {
if (node == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(node);
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
preResult.add(pop.val);
if (pop.right != null) {
stack.push(pop.right);
}
if (pop.left != null) {
stack.push(pop.left);
}
}
}
private void midPrint(List<Integer> midResult, TreeNode node) {
if (node == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(node);
TreeNode cur = node;
while (!stack.isEmpty()) {
if (cur != null) {
if (cur.left != null) {
stack.push(cur.left);
cur = cur.left;
} else {
cur = null;
}
} else {
TreeNode pop = stack.pop();
midResult.add(pop.val);
if (pop.right != null) {
stack.push(pop.right);
cur = pop.right;
} else {
cur = null;
}
}
}
}
private void afterPrint(List<Integer> afterResult, TreeNode node) {
if (node == null) {
return;
}
Stack<TreeNode> s1 = new Stack<TreeNode>();
Stack<Integer> s2 = new Stack<Integer>();
s1.push(node);
while (!s1.isEmpty()) {
TreeNode pop = s1.pop();
s2.push(pop.val);
if (pop.left != null) {
s1.push(pop.left);
}
if (pop.right != null) {
s1.push(pop.right);
}
}
while (!s2.isEmpty()) {
afterResult.add(s2.pop());
}
}
/** 下面为递归方式 **
private void prePrint(List<Integer> preResult,TreeNode node) {
if (node == null) {
return;
}
preResult.add(node.val);
prePrint(preResult, node.left);
prePrint(preResult, node.right);
}
private void midPrint(List<Integer> midResult, TreeNode node) {
if (node == null) {
return;
}
midPrint(midResult, node.left);
midResult.add(node.val);
midPrint(midResult, node.right);
}
private void afterPrint(List<Integer> afterResult, TreeNode node) {
if (node == null) {
return;
}
afterPrint(afterResult, node.left);
afterPrint(afterResult, node.right);
afterResult.add(node.val);
}
**/
}