590、N叉树的后序遍历
题目:
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树
:
返回其后序遍历: [5,6,3,2,4,1]
.
说明: 递归法很简单,你可以使用迭代法完成此题吗?
解答:
法一:
public IList<int> Postorder(Node root)
{
//和前序的方向不一样 5在第一个1在最后你
List<int> list = new List<int>();
return helper(root, list);
}
public List<int>helper(Node root, List<int> list)
{
if (root == null) return list;
//和上题一样的遍历每个节点的子节点
foreach (Node child in root.children)
{
helper(child, list);
}
list.Add(root.val);
return list;
}
法二:
public IList<int> Postorder1(Node root)
{
//和前序思路差不多,用insert
List<int> list = new List<int>();
if (root == null) return list;
Stack<Node> stack = new Stack<Node>();
stack.Push(root);
while (stack.Count != 0)
{
Node node = stack.Pop();
list.Insert(0, node.val);
for (int i = 0; i < node.children.Count; i++)
{
stack.Push(node.children[i]);
}
}
return list;
}