DFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public List<Integer> preorder(Node root) {
List<Integer> resultList = new ArrayList<>(); dfs(resultList, root); return resultList; }
private void dfs(List<Integer> resultList, Node node) { if (node == null) { return; }
resultList.add(node.val);
if (node.children != null) { for (Node child : node.children) { dfs(resultList, child); } } } }
|
Iterate
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
| class Solution { public List<Integer> preorder(Node root) {
List<Integer> resultList = new ArrayList<>();
Map<Node, Integer> nodeToNextChildIndexMap = new IdentityHashMap<>();
Stack<Node> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { while (root != null) { resultList.add(root.val); stack.push(root); int childIndex = nodeToNextChildIndexMap.getOrDefault(root, 0); nodeToNextChildIndexMap.put(root, childIndex + 1); root = getChild(root, childIndex); }
Node node = stack.pop(); int nextChildIndex = nodeToNextChildIndexMap.get(node); Node nextChild = getChild(node, nextChildIndex); if (nextChild != null) { root = nextChild; nodeToNextChildIndexMap.put(node, nextChildIndex + 1); stack.push(node); } else { nodeToNextChildIndexMap.remove(node); } }
return resultList; }
private Node getChild(Node node, int index) { if (node.children == null || index >= node.children.size()) { return null; }
return node.children.get(index); } }
|
Iterate
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
| class Solution { public List<Integer> preorder(Node root) {
List<Integer> resultList = new ArrayList<>();
Stack<Node> stack = new Stack<>(); if (root != null) { stack.push(root); }
while (!stack.isEmpty()) { Node node = stack.pop(); resultList.add(node.val);
if (node.children != null) { for (int i = node.children.size() - 1; i >= 0; i--) { stack.push(node.children.get(i)); } } }
return resultList; } }
|
References
589. N-ary Tree Preorder Traversal