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

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

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

先序遍历

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;
    }
posted @ 2020-07-18 11:16  IzuruKamuku  阅读(229)  评论(0编辑  收藏  举报