-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNAryTreeLevelOrderTraversal.java
More file actions
83 lines (67 loc) · 1.86 KB
/
NAryTreeLevelOrderTraversal.java
File metadata and controls
83 lines (67 loc) · 1.86 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package Leetcode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class Node
{
public int val;
public List<Node> children;
public Node()
{
}
public Node( int _val )
{
val = _val;
}
public Node( int _val, List<Node> _children )
{
val = _val;
children = _children;
}
};
public class NAryTreeLevelOrderTraversal
{
public static void main( String[] args )
{
List<Node> children = new ArrayList();
children.add( new Node( 3 ) );
children.add( new Node( 2 ) );
children.add( new Node( 4 ) );
Node root = new Node( 1, children );
NAryTreeLevelOrderTraversal nary = new NAryTreeLevelOrderTraversal();
List<List<Integer>> levelOrderResult = nary.levelOrder( root );
System.out.println( levelOrderResult );
}
public List<List<Integer>> levelOrder( Node root )
{
List<List<Integer>> result = new ArrayList();
LinkedList<Node> q = new LinkedList();
if( root == null )
return result;
q.add( root );
q.add( null );
List<Integer> currentResult = new ArrayList();
while( !q.isEmpty() )
{
Node temp = q.removeFirst();
if( temp != null )
{
currentResult.add( temp.val );
if( temp.children != null )
{
for( Node child : temp.children )
q.addLast( child );
}
}
else if( temp == null && !q.isEmpty() )
{
result.add( currentResult );
currentResult = new ArrayList();
q.addLast( null );
}
if(q.isEmpty())
result.add( currentResult );
}
return result;
}
}