-
589. N-ary Tree Preorder TraversalAlgorithm/java tip 2021. 3. 13. 11:39
leetcode.com/problems/n-ary-tree-preorder-traversal/
/* 자손이 N개인 트리의 pre-order */ class Solution { public List<Integer> preorder(Node root) { List<Integer> ret = new ArrayList<Integer>(); traverse(root, ret); return ret; } public void traverse(Node root, List<Integer> ret) { if(root == null) { return; } ret.add(root.val); for(Node child : root.children) { traverse(child, ret); } } // iterative public List<Integer> preorder(Node root) { Stack<Node> stk = new Stack<Node>(); List<Integer> preorder = new LinkedList<Integer>(); stk.push(root); if(root == null) { return preorder; } while(!stk.isEmpty()) { Node curr = stk.pop(); preorder.add(curr.val); for(int i = curr.children.size() - 1; i >= 0; i--) { stk.push(curr.children.get(i)); } } return preorder; } }
'Algorithm > java tip' 카테고리의 다른 글
21. Merge Two Sorted Lists (0) 2021.03.13 530. Minimum Absolute Difference in BST (0) 2021.03.13 78. Subsets (0) 2021.03.07 404. Sum of Left Leaves (0) 2021.03.06 22. Generate Parentheses (0) 2021.03.06