This problem was asked in Hacker Rank.
If you'd like to checkout Tree: Preorder Traversal.
Problem
Given a function which has a parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values.
Write a function:
function postOrder(node);
that, given a pointer of root node
and must print the values as a single line os space-separated values.
Examples
- Sample input:
1
\
2
\
5
/ \
3 6
\
4
Output:
4 3 6 5 2 1
- Sample input:
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Output:
4 5 2 6 8 7 3 1
Write an efficient algorithm for the following assumptions
1 <= Nodes in the tree <= 500
Solution
Javascript Solution
let result = [];
function postOrderTraversal(node) {
if (null == node) {
return;
}
postOrderTraversal(node.left);
postOrderTraversal(node.right);
result.push(node.data);
}
let root = {
data: 1,
left: { data: 2, left: { data: 4 }, right: { data: 5 } },
right: { data: 3, left: { data: 6 }, right: { data: 7, right: { data: 8 } } },
};
postOrderTraversal(root);
console.log(...result);
Java Solution
package com.pratap.sample.test;
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class BinaryTree {
void postOrderTraversal(Node node){
if(null == root){
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.print(root.data + " ");
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
tree.postOrderTraversal(tree.root);
}
}
Result
I have passed all the test cases.
💌 If you’d like to receive more coding solutions in your inbox, you can sign up for the newsletter here.
Discussions