前中后序二叉树遍历迭代方法总结

//inorder
    public List inorderTraversal(TreeNode root) {
        List res=new ArrayList<>();
        if (root==null) return res;

        Stack stack=new Stack<>();
        TreeNode curr=root;

        while(curr!=null || !stack.isEmpty()){
            while (curr!=null){
                stack.push(curr);
                curr=curr.left;
            }
            curr=stack.pop();
            res.add(curr.val);
            curr=curr.right;
        }
        return res;
    }

//preorder
    public List preorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        if(root == null) return list;
        Stack stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode current = stack.pop();
            list.add(current.val);
            if(current.right!=null) {
               stack.push(current.right);
            }
            if(current.left!=null) {
              stack.push(current.left);
            }
        }
        return list;
    }

//postorder
      public List postorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        if(root == null) return list;
        Stack stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            list.add(0,curr.val);
            if(curr.left!=null) {
              stack.push(curr.left);
            }
            if(curr.right!=null) {
               stack.push(curr.right); 
            }
        }
        return list;
    }

你可能感兴趣的:(前中后序二叉树遍历迭代方法总结)