class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } // Tree structure: // 1 // / \ // 2 3 // / \ // 4 5 void Postorder(Node root) { if (root == null) return; Postorder(root.Left); Postorder(root.Right); Console.Write(root.Value + " "); } // Call Postorder(root) where root is node with value 1
Remember postorder visits left subtree, then right subtree, then the root node.
Postorder traversal visits nodes in Left, Right, Root order. For the given tree, it visits 4, then 5, then 2, then 3, then 1.
class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } void Postorder(Node root) { if (root == null) return; Postorder(root.Left); Postorder(root.Right); Console.Write(root.Value + " "); } // Call Postorder(root) where root is node with value 10
Postorder visits left subtree first, then right subtree, then root.
Traverse left subtree (20), then right subtree (40, 50, 30), then root (10). So output is 20 40 50 30 10.
class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } void Postorder(Node root) { Postorder(root.Left); Postorder(root.Right); Console.Write(root.Value + " "); } // Called with a valid root node
Check if the code handles the case when root is null before accessing its members.
The code does not check if root is null before accessing root.Left, root.Right, and root.Value. This causes a NullReferenceException at runtime.
Postorder means visiting children before the parent.
Postorder traversal visits the left subtree first, then the right subtree, and finally the root node.
class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } Node Insert(Node root, int val) { if (root == null) return new Node(val); if (val < root.Value) root.Left = Insert(root.Left, val); else root.Right = Insert(root.Right, val); return root; } void Postorder(Node root) { if (root == null) return; Postorder(root.Left); Postorder(root.Right); Console.Write(root.Value + " "); } // Build tree by inserting 15,10,20,8,12,17,25 // Then call Postorder(root)
Build the BST step by step, then do postorder traversal (Left, Right, Root).
After inserting nodes, the BST structure is: 15 / \ 10 20 / \ / \ 8 12 17 25 Postorder visits left subtree (8,12,10), right subtree (17,25,20), then root (15).
