Untitled

 avatar
unknown
plain_text
a month ago
1.6 kB
1
Indexable
import java.util.*;

class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
        this.left = this.right = null;
    }
}

public class PostorderTraversalTwoStacks {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(root);

        // Modified preorder traversal
        while (!stack1.isEmpty()) {
            TreeNode node = stack1.pop();
            stack2.push(node);

            if (node.left != null) stack1.push(node.left); // Push left child first
            if (node.right != null) stack1.push(node.right); // Push right child second
        }

        // Pop nodes from stack2 for postorder traversal
        while (!stack2.isEmpty()) {
            result.add(stack2.pop().val);
        }

        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);

        PostorderTraversalTwoStacks pt = new PostorderTraversalTwoStacks();
        System.out.println(pt.postorderTraversal(root)); // Output: [4, 5, 2, 6, 7, 3, 1]
    }
}
Leave a Comment