zoukankan      html  css  js  c++  java
  • 数的三种遍历方式(迭代法)

    数的三种遍历方式(迭代法)

    思路:使用栈帮助存储树节点

    先序遍历

    public List<Integer> preorderTraversal(TreeNode root) {
    
            List<Integer> res = new ArrayList<>();
            Stack<TreeNode> s = new Stack<>();
            //防止输入为空
            if(root != null) {
                s.push(root);
            }
    
            while (!s.isEmpty()){
                //入栈时按照先右后左的顺序
                root = s.pop();
                if(root.right != null){
                    s.push(root.right);
                }
                if(root.left != null){
                    s.push(root.left);
                }
                res.add(root.val);
            }
    
            return res;
        }
    

    中序遍历

    public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            Stack<TreeNode> s = new Stack<>();
    
            while ( root != null ||!s.isEmpty()){
    
                //如果当前节点部位空,我们以它为根节点,和左节点迭代入栈
                while (root != null){
                    s.push(root);
                    s.push(root.left);
                    //以左节点为根循环
                    root = s.pop();
                }
    
                //经过上述循环后,root的左节点一定为空
                root = s.pop();
                res.add(root.val);
                //接着我们遍历其右子树,如果右子树为空,则从栈中拿出元素回溯,如果栈也为空,则完成遍历
                root = root.right;
            }
    
    
            return res;
        }
    

    后序遍历

    public List<Integer> post_order(TreeNode root){
    
            List<Integer> res = new ArrayList<>();
            Stack<TreeNode> s = new Stack<>();
    
            if(root != null) {
                s.push(root);
            }
    
            //按照先序遍历的顺序,先入左再入右,将结果翻转即可
            while (!s.isEmpty()){
                root = s.pop();
                res.add(root.val);
                if(root.left != null) {
                    s.push(root.left);
                }
                if(root.right != null){
                    s.push(root.right);
                }
            }
    
            Collections.reverse(res);
    
            return res;
        }
    
    因为我喜欢追寻过程中的自己
  • 相关阅读:
    记录一次电话面试
    记录一次git合并
    HTML通用属性与常见标签
    位运算的应用
    HTML总结
    前端MVC
    常用软件
    docker常用命令
    composer install(update)时出现killed
    优化小技巧:该怎么识别百度蜘蛛呢
  • 原文地址:https://www.cnblogs.com/IzuruKamuku/p/14359750.html
Copyright © 2011-2022 走看看