给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树 :
返回其前序遍历:
[1,3,5,6,2,4
]。
class Solution
{
public List
<Integer
> preorder
(Node root
) {
LinkedList
<Node
> stack
= new LinkedList
<>();
LinkedList
<Integer
> output
= new LinkedList
<>();
if (root
== null
) {
return output
;
}
stack.add
(root
);
while (!stack.isEmpty
()) {
Node node
= stack.pollLast
();
output.add
(node.val
);
Collections.reverse
(node.children
);
for (Node item
: node.children
) {
stack.add
(item
);
}
}
return output
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-28797.html