多叉树的前序遍历
2019-06-27 本文已影响0人
加油_汤姆叔叔
LeetCode原题:(https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/comments/)
class Solution {
public List<Integer> preorder(Node root) {
if(root == null) return new ArrayList<>();
Stack<Node> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
stack.push(root);
while(!stack.isEmpty()){
Node node = stack.pop();
result.add(node.val);
if (node.children != null && !node.children.isEmpty()) {
// 应该倒过来将子节点放入,因为在上文中使用的数据结构是栈
for (int i = node.children.size() - 1; i >= 0; i--) {
stack.push(node.children.get(i));
}
}
}
return result;
}
}