Press "Enter" to skip to content

Posts published in “Tree”

花花酱 LeetCode 501. Find Mode in Binary Search Tree

Problem

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
  • Both the left and right subtrees must also be binary search trees.

 

For example:
Given BST [1,null,2,2],

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

Solution1: Recursion w/ extra space

Time complexity: O(n)

Space complexity: O(n)

 

Solution2: Recursion w/o extra space

Two passes. First pass to find the count of the mode, second pass to collect all the modes.

Time complexity: O(n)

Space complexity: O(1)

 

花花酱 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