02_二叉树的迭代遍历

简介: 02_二叉树的迭代遍历

二叉树的迭代遍历

// 前序遍历顺序:中-左-右,入栈顺序:中-右-左
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> 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;
    }
}
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
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;
    }
}
相关文章
|
5月前
leetcode94二叉树的中序遍历(迭代做法)
leetcode94二叉树的中序遍历(迭代做法)
43 0
|
5月前
二叉树的统一迭代遍历法
二叉树的统一迭代遍历法
34 0
|
4月前
|
存储 SQL 算法
LeetCode 题目 94:五种算法递归|迭代|莫里斯|线索二叉树|栈的迭代二叉树 实现中序遍历
LeetCode 题目 94:五种算法递归|迭代|莫里斯|线索二叉树|栈的迭代二叉树 实现中序遍历
|
11月前
|
算法 C++
87 C++ - 常用遍历算法
87 C++ - 常用遍历算法
39 0
|
算法
用递归的思想实现二叉树前、中、后序迭代遍历
用递归的思想实现二叉树前、中、后序迭代遍历
61 1
二叉树的遍历(递归And迭代)
二叉树的遍历(递归And迭代)
43 0
|
存储 编译器
二叉树的递归遍历与迭代遍历(图示)
本文将讲述二叉树递归与迭代的相关知识。
119 0
二叉树的三种遍历方式
二叉树的三种遍历方式
217 0
二叉树的三种遍历方式
|
存储 机器学习/深度学习 人工智能
关于哈密顿路是否存在的遍历算法
我是怎么也没想到这个问题陪伴了我快十年的时光,占到了我生命的一半时光(当然不可能一直在死磕这道题),十年中每每学到一些新的知识都会进行一些尝试,但很多时候还是无功而返,大概在十天前复习数据结构相关知识的时候偶然发现了一个简单而且有趣的公式,然后灵感就来了,不过有一点点遗憾的是身为学数学的出身的,未能使用纯数学的方式解决,有一点点丢人,话不多说,请看正文。
126 0
关于哈密顿路是否存在的遍历算法