예제 #1
0
        ///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);
        }
예제 #2
0
        ///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);
        }
예제 #3
0
 ///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));
 }
예제 #4
0
 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);
 }