Press "Enter" to skip to content

Posts tagged as “n-ary”

花花酱 LeetCode 429. N-ary Tree Level Order Traversal

Problem

Given an n-ary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

 

 

We should return its level order traversal:

[
     [1],
     [3,2,4],
     [5,6]
]

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Solution1: Recursion

Time complexity: O(n)

Space complexity: O(n)

C++

Solution2: Iterative

 

花花酱 LeetCode 559. Maximum Depth of N-ary Tree

Problem

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

 

 

We should return its max depth, which is 3.

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Solution: Recursion

Time complexity: O(n)

Space complexity: O(n)

Related Problems

花花酱 LeetCode 590. N-ary Tree Postorder Traversal

Problem

Given an n-ary tree, return the postorder traversal of its nodes’ values.

 

For example, given a 3-ary tree:

 

Return its postorder traversal as: [5,6,3,2,4,1].

 

Note: Recursive solution is trivial, could you do it iteratively?

 

Solution 1: Recursive

C++

Solution 2: Iterative

C++

Related Problems

花花酱 LeetCode 589. N-ary Tree Preorder Traversal

Problem

Given an n-ary tree, return the preorder traversal of its nodes’ values.

 

For example, given a 3-ary tree:

 

Return its preorder traversal as: [1,3,5,6,2,4].

 

Note: Recursive solution is trivial, could you do it iteratively?

Solution1: Recursive

Solution2: Iterative

Related Problems