【算法】二叉树前中后序遍历 - 迭代版

wallhaven-4vyoep.jpg
二叉树遍历有前、中、后序遍历三种,用递归法解决没什么意思,解题过程中会忽略很多的东西,下面我们用栈模拟这个递归的过程。

前序遍历
遍历流程:根 -> 左 -> 右

/**
     * 前序遍历 - dfs - 迭代版
     * @param root	根节点
     * @return
*/
public static List<Integer> preorderTraversal(TreeNode root){
        List<Integer> res = new LinkedList<>();
        if(root == null){
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null){
            while (root != null){		// 不断向左子节点深入
                stack.push(root);
                res.add(root.val);
                root = root.left;
            }
            root = stack.pop();		// 当叶子节点为 null 时,出栈
            root = root.right;
        }
        return res;
    }
    

中序遍历
遍历顺序:左 -> 中 -> 右

/**
   	 * 中序遍历 - dfs - 迭代版
     * @param root
     * @return
*/
public static List<Integer> inOrderTraversal(TreeNode root) {
    List<Integer> res = new LinkedList<>();
    if (root == null) {
        return res;
    }
    Stack<TreeNode> stack = new Stack<>();
    while (!stack.isEmpty() || root != null) {  // root 不为空说明还能接着进栈,stack 不为空说明还能够出栈
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        res.add(root.val);
        root = root.right;
    }
    return res;
}

发现算法的套路,并不断学习,才能进步!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值