模拟系统栈实现二叉树前序遍历

在这里插入图片描述

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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值