[Leet Code] All Elements in Two Binary Search Trees

Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]
Input: root1 = [], root2 = [5,1,7,0,2]
Output: [0,1,2,5,7]
Input: root1 = [0,-10,10], root2 = []
Output: [-10,0,10]
Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getAllElements(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: List[int]
"""
elements = []
self.traverse(root1, elements)
self.traverse(root2, elements)
return sorted(elements)

def traverse(self, root, elements):
if root:
self.traverse(root.left, elements)
elements.append(root.val)
self.traverse(root.right, elements)

--

--

--

Learning, and posting my findings!

Love podcasts or audiobooks? Learn on the go with our new app.

Quasar Framework: Tutorial part 1 — Introduction

How to implement Logout due to Inactivity Functionality (Detect User Inactivity) in front-end…

Angular Style Guide

What the React? Your first 30 seconds with Smartcar

javascript object-oriented programming — 4 key concepts

End-to-end(E2E) Testing for Vue.js application using Testcafe

React Hooks

4 Best JavaScript Books for Beginners

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Boyd

Matthew Boyd

Learning, and posting my findings!

More from Medium

103. Binary Tree Zigzag Level Order Traversal 🚀

Binary Search(3) / Algorithm

Identify Complete Binary Tree — Leetcode 958

Merge Sorted Array🐧