-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodePost-OrderTraversal.java
More file actions
59 lines (53 loc) · 1.8 KB
/
CodePost-OrderTraversal.java
File metadata and controls
59 lines (53 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Code : Post-order Traversal
// Send Feedback
// Given a generic tree, print the post-order traversal of given tree.
// The post-order traversal is: visit child nodes first and then root node.
// For the given tree, the post order traversal will be 40 50 20 30 40 10
// Input format:
// The first line of input contains data of the nodes of the tree in level order
// form. The order is: data for root node, number of children to root node, data
// of each of child nodes and so on and so forth for each node. The data of the
// nodes of the tree is separated by space.
// Output Format :
// The first and only line of output contains the elements printed in post-order
// traversal. The elements in the output must be separated by a single space.
// Constraints:
// Time Limit: 1 sec
// Sample Input 1:
// 10 3 20 30 40 2 400 50 0 0 0 0
// Sample Output 1:
// 400 50 20 30 40 10
// Explanation
// For 10 , total 3 children are there : 20 30 40
// For 20, total 2 children are there : 400 50
// So, the output will be 400 50 20 30 40 10
public class Solution {
/*
* TreeNode structure
*
* class TreeNode<T> {
* T data;
* ArrayList<TreeNode<T>> children;
*
* TreeNode(T data){
* this.data = data;
* children = new ArrayList<TreeNode<T>>();
* }
* }
*/
public static void printPostOrder(TreeNode<Integer> root) {
/*
* Your class should be named Solution.
* Don't write main() function.
* Don't read input, it is passed as function argument.
* Print output as specified in the question
*/
if (root == null) {
return;
}
for (int i = 0; i < root.children.size(); i++) {
printPostOrder(root.children.get(i));
}
System.out.print(root.data + " ");
}
}