leetcode hot 100

二叉树遍历(迭代)

二叉树的遍历不仅可以用递归来做,也可以用迭代来做。二叉树的递归底层是采用栈来进行的,所以我们迭代就要采用栈来做。

我们知道,栈的原则是先进后出,以前序为例,顺序是中左右,那么,以根节点开始,如果不为空,我们先把根节点压入栈,然后弹出,然后再把右节点压入栈,再把左节点压入栈,之后再按顺序弹出即可。

复制代码
// 前序遍历顺序:中-左-右,入栈顺序:中-右-左
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            result.add(node.val);
            if (node.right != null){
                stack.push(node.right);
            }
            if (node.left != null){
                stack.push(node.left);
            }
        }
        return result;
    }
}

与前序做对比的是后续,只需要记住,将前序进栈的顺序倒过来,最后再反转数组即可

复制代码
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            result.add(node.val);
            if (node.left != null){
                stack.push(node.left);
            }
            if (node.right != null){
                stack.push(node.right);
            }
        }
        Collections.reverse(result);
        return result;
    }
}

中序就与前后序不同了,中序过程中,我们的顺序应该是左右中,所以,我们要处理的节点不是我们遍历到的节点,我们可以用一个指针来记录我们遍历到的节点,并使其进栈,之后遍历其左右节点即可

复制代码
// 中序遍历顺序: 左-中-右 入栈顺序: 左-右
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()){
           if (cur != null){
               stack.push(cur);
               cur = cur.left;
           }else{
               cur = stack.pop();
               result.add(cur.val);
               cur = cur.right;
           }
        }
        return result;
    }
}
相关推荐
向阳@向远方35 分钟前
第二章 简单程序设计
开发语言·c++·算法
github_czy1 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
许愿与你永世安宁2 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子2 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
满分观察网友z2 小时前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法
YuTaoShao3 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
Heartoxx3 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
大熊背3 小时前
图像处理专业书籍以及网络资源总结
人工智能·算法·microsoft
满分观察网友z3 小时前
别怕树!一层一层剥开它的心:用BFS/DFS优雅计算层平均值(637. 二叉树的层平均值)
算法
杰克尼4 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode