【leetcode刷题记录】二叉树遍历

中序遍历

java 复制代码
public List<Integer> inorderTraversal(TreeNode root) {
//        List<Integer> result = new ArrayList<>();
//        midAccTree(result,root);
//        return result;

        //栈迭代解决
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            result.add(root.val);
            root = root.right;
        }
        return result;
    }



    //中序遍历方法
//    public void midAccTree(List<Integer> res,TreeNode root){
//        if (root == null) return;
//        midAccTree(res,root.left);
//        res.add(root.val);
//        midAccTree(res,root.right);
//
//    }

后序遍历

java 复制代码
public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode preNode = null;
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == preNode){
                res.add(root.val);
                preNode = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
相关推荐
菜地里的小菜鸟3 小时前
将linux程序打成.run包
linux·将linux程序打成run包·运维自动安装包
圣光SG5 小时前
Java操作题练习(七)
java·开发语言·算法
晚风吹长发6 小时前
Docker基础——Docker Network(网络详解)
linux·运维·网络·ubuntu·docker·容器
Cx330_FCQ6 小时前
Tmux使用
服务器·git·算法
高磊20057 小时前
LVS(Linux virual server)
linux·服务器·lvs
拳里剑气7 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510308 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1238 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
执笔画流年呀8 小时前
Linux搭建Java项目部署环境
java·linux·运维
Sisphusssss9 小时前
香橙派5plus GPIO
linux·python·ubuntu