给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
返回其后序遍历:
[5,6,3,2,4,1
].
class Solution
{
public List
<Integer
> postorder
(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.addFirst
(node.val
);
for (Node item
: node.children
) {
if (item
!= null
) {
stack.add
(item
);
}
}
}
return output
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-30027.html