import java.util.EmptyStackException;
import java.util.Stack;
public class PreOrderTest {
public static void main(String[] args) {
/**
* 解法一、递归法:要理解递归的思路并且熟练的使用它,就是要想清楚你想做什么,什么时候停止。
*
* 解法二、迭代法:用栈来模拟递归实现
*/
int[] arr = {1,2,3,4,5,6,7};
BinTree tree = new BinTree();
tree.created(arr);
preOrderInteraction01(tree.getRoot());
System.out.println();
try {
preOrderInteraction02(tree.getRoot());
} catch (EmptyStackException e) {
e.printStackTrace();
}
}
public static void preOrderInteraction01(BinTree e) {
if (e == null) {
return;
}
// 1.遍历 处理(打印)根节点
System.out.print(" " + e.val);
// 1.遍历 处理(打印)左节点
preOrderInteraction01(e.getlChild());
// 1.遍历 处理(打印)右节点
preOrderInteraction01(e.getrChild());
}
public static void preOrderInteraction02(BinTree r) throws EmptyStackException {
//校验数据
if (r == null) {
return;
}
Stack<BinTree> stack = new Stack<>();
stack.push(r);
// BinTree cur = r;
while (stack != null) {
BinTree cur = stack.pop();
System.out.print(" " + cur.val);
if (cur.getrChild() != null) {
stack.push(cur.getrChild());
}
if (cur.getlChild() != null) {
stack.push(cur.getlChild());
}
}
}
}