You are on page 1of 59

Print All Paths Of A Tree

Given a binary tree, return all paths from root to leaf.

Example One

Output:

[
[1, 2, 4],
[1, 2, 5],
[1, 3, 6],
[1, 3, 7]
]
There are four leafs in the given graph, so we have four paths: from the root to every leaf. Each
path is a list of the values from the tree nodes on the path, and we have four lists. They can go in
any order.

Example Two

Output:

[
[10, 20, 40],
[10, 20, 50],
[10, 30]
]
There are 3 paths in the tree.

The leftmost path contains values: 10 -> 20 -> 40

The rightmost path contains values: 10 -> 30

The other path contains values: 10 -> 20 -> 50

The order of the paths (order of the lists in the outer list) does not matter, so [[10, 30], [10, 20,
40], [10, 20, 50]] is another correct answer.

Notes
 Return a list of integer lists, where each list is representing a path.
 The order of the paths (order of the lists in the outer list) does not matter.

Constraints:

 0 <= number of nodes in the given tree <= 105


 -109 <= value in a node <= 109

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def all_paths_of_a_binary_tree(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_list_int32
"""

# Write your code here.

return []

PostOrder Traversal Without Recursion


Given a binary tree, find its post-order traversal without using recursion.

Example

Output:

[400, 500, 200, 300, 100]

Notes
Constraints:

 1 <= number of nodes <= 105


 -109 <= value in a node <= 109

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None
self.right = None

"""

def postorder_traversal(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_int32

"""

# Write your code here.

return []

Problem

Lowest Common Ancestor


Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

The LCA of nodes a and b in a tree is defined as the shared ancestor node of a and b that is
located farthest from the root of the tree.

Example
a = 8, b = 9
Output:

5
There are three shared parents of 8 and 9 in this tree: 5, 2, 1. Of those three, the farthest from the
root is 5.

Other examples:
LCA(2, 5) = 2
LCA(2, 3) = 1

Notes

 A node is considered its own ancestor and its own descendant.


 Return the value of the LCA node of the two given nodes.

Constraints:

 1 <= number of nodes <= 100000


 1 <= node value <= number of nodes
 Node values are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def lca(root, a, b):

"""

Args:

root(BinaryTreeNode_int32)

a(BinaryTreeNode_int32)

b(BinaryTreeNode_int32)

Returns:

int32
"""

# Write your code here.

return 0

Problem

In-order Binary Tree Iterator


Design and implement an iterator for the in-order traversal of a binary tree.

Given the root node of a tree of positive numbers, and a sequence of operations on the iterator,
calculate return values of all those operations.
Iterator has two operations:

1. has_next() should return 1 if one or more elements remain in the in-order traversal of the
tree, otherwise it should return 0.
2. next() should return the next value in the in-order traversal of the tree if it exists,
otherwise a special value of 0.

Execute operations one by one and return all their return values in a list.
Both operations must take constant time on average and use O(height of the tree) of extra
memory.

Example

"operations": ["next", "has_next", "next", "next", "has_next", "has_next", "next"]


Output:

[100, 1, 200, 300, 0, 0, 0]


In-order traversal for the given tree is [100, 200, 300].

1st operation next() returns the first element, 100.


2nd operation has_next() returns 1 because traversal isn't over and there are more elements.
3rd operation, next() returns the second element, 200.
4th operation, next() returns the last element, 300.
5th operation has_next() returns 0; the in-order traversal is over.
6th operation has_next() returns 0; it's still over.
7th operation next() return 0, since there is no next element.

Notes

 It is a good idea to implement the iterator as a class (or object or struct - depending on
the language you use). In function implement_tree_iterator you would then create an
instance of that class/object/struct and call its methods/functions to execute the
operations.
 Structure of the class may look like this:
 class TreeIterator {
 TreeIterator() {
 // This is a constructor.
 // Initialize required data structures.
 }

 int next() {
 // ...
 }

 int has_next() {
 // Or you can return bool here and convert it
 // to int in function implement_tree_iterator.
 }
 }
Constraints:

 1 <= number of nodes in the tree <= 100000


 1 <= node value <= 109
 0 <= number of operations <= 300000

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def implement_tree_iterator(root, operations):


"""

Args:

root(BinaryTreeNode_int32)

operations(list_str)

Returns:

list_int32

"""

# Write your code here.

return []

Problem

Mirror Image Of Binary Tree


Given the root of a binary tree, transform the tree in-place into its mirror image.

Example
0
/ \
1 2
/ \ / \
3 4 5 6
Output:

0
/ \
2 1
/ \ / \
6 5 4 3

Notes

 The function doesn't need to return anything. Modify the tree in-place.

Constraints:

 1 <= number of nodes <= 100000


 0 <= node value < number of nodes
 Node values are unique
"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def mirror_image(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

Nothing

"""

# Write your code here.

Problem

Clone A Binary Tree


Given the root node of a binary tree, clone it (clone every node of the tree) and return the root
node of the cloned tree.

Example
Output:

Notes

Constraints:

 0 <= number of nodes <= 100000


 -109 <= node value <= 109
"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def clone_tree(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

Problem

Populate Sibling Pointers


Given a binary tree, populate next_right pointers in all nodes and return the root of the tree.
Every node will have left and right pointers as usual in a binary tree. In addition, it will
have next_right pointer which will be initialized to null.
The goal is to populate the next_right such that it points to the next node to the right at the
same level of the tree. The rightmost node on every level of the tree should keep next_right ==
null.

Example
Output:

The tree has three levels.


Level 1: 100.
Level 2: 200, 300.
Level 3: 400, 500, 600, 700.

There is nothing to the right of the root node on the first level, so root.next_right == null.
First node of the seconds level points to the second node on the second level. Second node of
the second level has next_right == null.
And so on.

Notes

 Return the root of the tree after populating next_right pointers.

Constraints:

 0 <= number of nodes <= 100000


 0 <= node value <= 109

Description of the text format of the test cases

You might need this for debugging your solution on IK UpLevel platform.

Input file contains the given tree in the usual binary tree format, there is nothing
about next_right in the input file.
Output file, if the solution is correct, contains the same tree but includes the information stored
in the next_right pointers. As in the input, the tree is represented by a JSON array. null values
from input remain null values in the output. Non-null values (numbers) represent actual nodes of
the tree in the input. In the output, a node instead is represented by a JSON arrays with two
elements. For example, if node value was 5 in the input, then in the output it should either be [5,
null] if node.next_right == null or [5, 6] if node.next_right.value == 6.
Example output

is represented by

[[100, null],
[200, 300], [300, null],
[400, 500], [500, 600], [600, 700], [700, null]]

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

self.next_right = None

"""

def populate_sibling_pointers(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.


return None

Problem

Level Order Traversal Of A Binary Tree


Given a binary tree, list the node values level by level from left to right.

Example One

Output:

[
[0],
[1],
[2],
[4],
[3]
]

Example Two
Output:

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

Notes

Constraints:

 1 <= number of nodes in the given tree <= 20000


 0 <= node value < number of nodes
 Node values are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def level_order_traversal(root):

"""
Args:

root(BinaryTreeNode_int32)

Returns:

list_list_int32

"""

# Write your code here.

return []

Problem

Level Order Traversal Of A Tree


Given a tree, list node values level by level from left to right.

Example One

Output:

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

Example Two
Output:

[
[1],
[2],
[4],
[3]
]

Notes

Constraints:

 1 <= number of nodes <= 20000


 1 <= value in a node <= number of nodes
 Node values are unique
 Root node's value is 1

"""

For your reference:

class TreeNode:

def __init__(self, value):

self.value = value

self.children = []

"""

def level_order(root):

"""
Args:

root(TreeNode_int32)

Returns:

list_list_int32

"""

# Write your code here.

return []

Problem

Reverse Level Order Traversal Of A Binary


Tree
Given a binary tree, return the bottom-up level order traversal of the node values listing each
level from left to right.

Example One

Output:

[
[3, 4],
[1, 2],
[0]
]

Example Two

Output:

[
[3],
[2],
[1],
[0]
]

Notes

Constraints:

 1 <= number of nodes in the given tree <= 20000


 0 <= node value < number of nodes
 Node values are unique

"""
For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def reverse_level_order_traversal(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_list_int32

"""

# Write your code here.

return []

Right Side View Of A Binary Tree


Given a binary tree, imagine yourself standing on the right side of it and return a list of the node
values that you can see from the top to the bottom.

Example One
Output:

[0, 2, 4]
From the right side, the tree will look like below:

Example Two
Output:

[0, 1, 2, 3]

Notes
Constraints:

 1 <= number of nodes in the tree <= 20000


 0 <= node value < number of nodes in the tree
 Node values are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""
def right_view(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_int32

"""

# Write your code here.

return []

Problem

Zigzag Level Order Traversal Of A Binary Tree


Given a binary tree, return the zigzag level order traversal of the node values listing the odd
levels from left to right and the even levels from right to left.

Example One

Output:

[
[0],
[2, 1],
[3, 4]
]

Example Two

Output:

[
[0],
[1],
[2],
[3]
]

Notes

Root node is considered to be at the level 1.

Constraints:

 1 <= number of nodes in the given tree <= 20000


 0 <= node value < number of nodes
 Node values are unique
"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def zigzag_level_order_traversal(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_list_int32

"""

# Write your code here.

return []

Problem

Root To Leaf Path Sum Equal To K


Given a binary tree and an integer k, check whether the tree has a root to leaf path with a sum of
values equal to k.

Example One
k = 4
Output:

1
Path 0 -> 1 -> 3 has the sum of node values equal to 4.

Example Two

k = 10
Output:

Notes

Constraints:

 1 <= number of nodes in the tree <= 105


 -105 <= node value <= 105
 -109 <= k <= 109
"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def path_sum(root, k):

"""

Args:

root(BinaryTreeNode_int32)

k(int32)

Returns:

bool

"""

# Write your code here.

return False

Problem

Is It A BST
Given a binary tree, check if it is a binary search tree (BST). A valid BST does not have to be
complete or balanced.

Consider this definition of a BST:

1. All nodes values of left subtree are less than or equal to parent node value.
2. All nodes values of right subtree are greater than or equal to parent node value.
3. Both left subtree and right subtree must be BSTs.
4. NULL tree is a BST.
5. Single node trees (including leaf nodes of any tree) are BSTs.

Example One

Output:

0
Left child value 200 is greater than the parent node value 100; violates the definition of BST.

Example Two

Output:

Notes

 Return true if the input tree is a BST or false otherwise.

Constraints:

 0 <= number of nodes <= 100000


 -109 <= values stored in the nodes <= 109
"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def is_bst(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

bool

"""

# Write your code here.

return False

Problem

Single Value Tree


Given a binary tree, find the number of unival subtrees. An unival (single value) tree is a tree that
has the same value in every node.

Example One
Output:

6
The input tree has a total of 6 nodes. Each node is a root of a subtree. All those 6 subtrees are
unival trees.

Example Two

Output:

5
The input tree has a total of 7 nodes, so there are 7 subtrees. Of those 7, all but two subtrees are
unival. The two non-unival subtrees are:

1. The one rooted in the root node and


2. The one rooted in the root's right child.
Notes

Constraints:

 0 <= number of nodes in the tree <= 105


 -109 <= node value <= 109

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def find_single_value_trees(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

int32

"""

# Write your code here.

return 0

Problem

Upside Down
Given a binary tree where every node has either 0 or 2 children and every right node is a leaf
node, flip it upside down turning it into a binary tree where all left nodes are leafs.
Example One

Output:

Example Two

Output:
The same output tree oriented differently:

Notes

 Return the root of the output tree.

Constraints:

 0 <= number of nodes <= 100000


 1 <= node value <= 100000

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None
self.right = None

"""

def flip_upside_down(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

Problem

Merge Two BSTs


Given two Binary Search Trees (BSTs), merge them into a single height-balanced BST.

Example One

Output:
Example Two

Output:
Notes

 A node with value equal to the value of the root node can be inserted either in the left or
right subtree.
 A binary tree is called height-balanced if for each node the following property is satisfied:
o The difference in the heights of its left and right subtrees differ by at most 1.

Constraints:

 1 <= number of nodes in the given BSTs <= 104


 -109 <= node value <= 109
"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def merge_two_binary_search_trees(root1, root2):

"""

Args:

root1(BinaryTreeNode_int32)

root2(BinaryTreeNode_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

Problem

Largest BST
Given a binary tree, find the largest subtree that's a binary search tree (BST).

Here the largest subtree means a subtree with maximum number of nodes.

Example
Output:

3
There are seven distinct subtrees. Five of them are BSTs (rooted in 300, 200, 400, 600, 700). Sizes
if those five are 3, 1, 1, 1 and 1 respectively. The largest BST subtree has 3 nodes.

Notes

 There is only one argument named root denoting the root of the input tree.
 Return an integer denoting the size of the largest BST.

Constraints:

 0 <= number of nodes <= 100000


 -109 <= values stored in the nodes <= 109

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def find_largest_bst(root):

"""

Args:

root(BinaryTreeNode_int32)
Returns:

int32

"""

# Write your code here.

return 0

Problem

Convert A Binary Tree Into A Circular Doubly


Linked List
Given the root node of a binary tree, convert it into a circular doubly linked list in-place. The left
and the right pointers in nodes are to be used as previous and next pointers, respectively, in the
structure that you return.

Returned list should follow the in-order traversal order of the given tree.

The "root" node that you return should be the first node in the in-order traversal order. That
"root" node should be connected with the last node in the in-order traversal as if "root" node
goes after the last node and last node goes before the "root" node.

Example

Output:
Notes

Constraints:

 1 <= number of nodes <= 105


 -109 <= node value <= 109

Description of the text format of the test cases

You might need this for debugging your solution on IK UpLevel platform.

Input file contains the given tree in the usual binary tree format.

Output file lists node values of the returned data structure:

 starting from the returned node,


 following right pointers until we reach the last node in the list,
 then following left pointers until we come back to the root node.

Example output

is represented by

[1, 2, 3, 4, 5, 4, 3, 2, 1]
If the returned data structure is not circular or otherwise incorrect, the output may contain the
correct portion of it, and you will find an error message in the ERROR field.

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def binary_tree_to_cdll(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

Problem

Construct Binary Tree


Given inorder and preorder traversal of a valid binary tree, you have to construct the binary tree.

Example One
{
"inorder": [2, 1, 3],
"preorder": [1, 2, 3]
}
Output:
1
/ \
2 3

Example Two
{
"inorder": [3, 2, 1, 5, 4, 6],
"preorder": [1, 2, 3, 4, 5, 6]
}
Output:

1
/ \
2 4
/ / \
3 5 6

Notes

 Return the root node of the constructed binary tree.

Constraints:

 0 <= n <= 105


 1 <= inorder[i], preorder[i] <= 105
 Values stored in the binary tree are unique.

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def construct_binary_tree(inorder, preorder):

"""

Args:

inorder(list_int32)
preorder(list_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

Problem

Preorder Traversal Of A Binary Tree


Given a binary tree, return node values in the preorder traversal order.

Example One

Output:

[0, 1, 3, 4, 2]

Example Two
Output:

[0, 1, 2, 3]

Notes

The preorder traversal processes all the nodes of a binary tree by first visiting the root, then
recursively visiting its left and right subtrees respectively.

Constraints:

 1 <= number of nodes in the given tree <= 20000


 0 <= node value < number of nodes
 Node values are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None
self.right = None

"""

def preorder(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_int32

"""

# Write your code here.

return []

Problem

Inorder Traversal Of A Binary Tree


Given a binary tree, return the inorder traversal of its node values.

Example One

Output:

[3, 1, 4, 0, 2]
Example Two

Output:

[1, 3, 2, 0]

Notes

The inorder traversal of a binary tree first visits the left subtree, then the root and finally the right
subtree.

Constraints:

 1 <= number of nodes in the given tree <= 20000


 0 <= node value < number of nodes
 Node values are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):


self.value = value

self.left = None

self.right = None

"""

def inorder(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_int32

"""

# Write your code here.

return []

Problem

Inorder Traversal Of A Binary Tree


Given a binary tree, return the inorder traversal of its node values.

Example One
Output:

[3, 1, 4, 0, 2]

Example Two

Output:

[1, 3, 2, 0]

Notes

The inorder traversal of a binary tree first visits the left subtree, then the root and finally the right
subtree.

Constraints:

 1 <= number of nodes in the given tree <= 20000


 0 <= node value < number of nodes
 Node values are unique

"""
For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def inorder(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_int32

"""

# Write your code here.

return []

Problem

Postorder Traversal Of A Binary Tree


Given a binary tree, find its postorder traversal.

Example One
Output:

[3, 4, 1, 2, 0]

Example Two

Output:

[3, 2, 1, 0]
Notes

The postorder traversal visits all the nodes of a binary tree by recursively visiting the left subtree,
then the right subtree and finally visiting the root.

Constraints:

 1 <= number of nodes in the tree <= 20000


 0 <= node value < number of nodes
 No two nodes have the same value

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def postorder(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

list_int32

"""

# Write your code here.

return []

Problem
Print All Paths That Sum To K
Given a binary tree and an integer k, find all the root to leaf paths that sum to k.

Example One

k = 80
Output:

[
[10, 25, 45]
[10, 30, 40]
]

Example Two

k = 10
Output:

[
[5, 5],
[5, 5]
]

Notes
 In case there is no root to leaf path with a sum equal to k, return [[-1]].
 The order of the paths (order of the lists in the outer list) does not matter.

Constraints:

 1 <= number of nodes <= 104


 -105 <= value in a node <= 105
 -109 <= k <= 109

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def all_paths_sum_k(root, k):

"""

Args:

root(BinaryTreeNode_int32)

k(int32)

Returns:

list_list_int32

"""

# Write your code here.

return []

Problem

Diameter Of A Binary Tree


Given a binary tree, find its diameter.
Example One

Output:

Example Two

Output:

Notes

 Diameter of a binary tree is the length of the longest path between any two nodes of the
tree.
 Length between any two nodes is equal to the number of edges traversed to reach one
node from the other.
Constraints:

 1 <= number of nodes in the given tree <= 105


 0 <= node value < number of nodes
 Node values are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def binary_tree_diameter(root):

"""

Args:

root(BinaryTreeNode_int32)

Returns:

int32

"""

# Write your code here.

return 0

Problem

Convert Sorted List To Binary Search Tree


Given a linked list with elements sorted in ascending order, convert it into a height-balanced
binary search tree.

Example One
Output:

Example Two

Output:

Notes

 A binary tree is called height-balanced if for any node, the difference in the heights of its
left and right subtree does not exceed one.
 Input list does not contain duplicates.
 Return the root node of the created hight-balanced BST.

Constraints:
 1 <= length of the linked list <= 20000
 -109 <= node value <= 109

"""

For your reference:

class LinkedListNode:

def __init__(self, value):

self.value = value

self.next = None

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def sorted_list_to_bst(head):

"""

Args:

head(LinkedListNode_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

Problem
Construct A Binary Search Tree From Its
Preorder Traversal
Construct a Binary Search Tree whose preorder traversal matches the given list.

Example One
{
"preorder": [1, 0, 2]
}
Output:

Example Two
{
"preorder": [2, 0, 1, 3, 5, 4]
}
Output:

Notes
Constraints:

 1 <= size of the given list <= 105


 -109 <= number in the list <= 109
 Numbers in the given list are unique

"""

For your reference:

class BinaryTreeNode:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

"""

def build_binary_search_tree(preorder):

"""

Args:

preorder(list_int32)

Returns:

BinaryTreeNode_int32

"""

# Write your code here.

return None

You might also like