///590. N-ary Tree Postorder Traversal ///Given the root of an n-ary tree, return the postorder traversal of its nodes' values. public IList <int> Postorder(Node_Childs root) { var ans = new List <int>(); PostorderNaryTree(root, ans); return(ans); }
///429. N-ary Tree Level Order Traversal ///Given an n-ary tree, return the level order traversal of its nodes' values. public IList <IList <int> > LevelOrder(Node_Childs root) { var ans = new List <IList <int> >(); var nodes = new List <Node_Childs>() { root }; while (nodes.Count > 0) { var next = new List <Node_Childs>(); var list = new List <int>(); foreach (var n in nodes) { if (n == null) { continue; } list.Add(n.val); next.AddRange(n.children); } if (list.Count > 0) { ans.Add(list); } nodes = next; } return(ans); }
///559. Maximum Depth of N-ary Tree ///Given a n-ary tree, find its maximum depth. public int MaxDepth(Node_Childs root) { if (root == null) { return(0); } return(1 + MaxDepth(root.children)); }
public void PostorderNaryTree(Node_Childs node, IList <int> ans) { if (node == null) { return; } foreach (var child in node.children) { if (child != null) { PostorderNaryTree(child, ans); } } ans.Add(node.val); }