import java.util.*;
public class Main {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//系统指令
public class Command{
String type; //指令分两种,一种是访问 go,一种是执行print
TreeNode node;
public Command(String type,TreeNode node){
this.type = type;
this.node = node;
}
}
public static void main(String[] args) {
}
public List<Integer> preorderTraversal(TreeNode root) {
Stack<Command> sysStack = new Stack<Command>(); //系统栈
List<Integer> list = new ArrayList<Integer>();
if (root != null){
sysStack.push(new Command("go",root));
}
while (!sysStack.isEmpty()){
Command cmd = sysStack.pop();
if (cmd.type == "go"){
//由于栈是后进先出,所以这里入栈的顺序和遍历的顺序相反
//只要改变下面三部分的执行顺序,就可以变为中序遍历和前序遍历
if (cmd.node.right != null){
sysStack.push(new Command("go",cmd.node.right));
}
if (cmd.node.left != null){
sysStack.push(new Command("go",cmd.node.left));
}
sysStack.push(new Command("print",cmd.node));
}else {
assert cmd.type == "print";
list.add(cmd.node.val);
}
}
return list;
}
}
模拟系统栈实现二叉树前序遍历
最新推荐文章于 2024-05-29 16:57:33 发布