All the elements LeetCode- two binary search tree

Note: LeetCode-- tree theme.

题目链接(1305):https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees/

Subject description:

For you  root1 and  root2 this two binary search tree.

Please return a list containing all integers sorted in ascending order of two trees. .

Example:

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: the root1 = [], root2 = [5,1,7,0,2 ]
Output: [0, 1,2,5,7]

....

Problem-solving ideas:

About binary tree, my first thought is recursive. According to subject, it is clear that each node to traverse the binary tree, obtain the value of the node, and sort them.

Code:

the TreeNode class: 
DEF the __init __ (Self, X):
self.val = X
self.left = None
self.right = None

class Solution:
DEF getAllElements (Self, the root1: the TreeNode, root2: the TreeNode) -> List [int]:
L = []
self.getroot (root1, L) # root1 obtain the value of each node in
self.getroot (root2, l) # Get the value of each node root2
        l.sort () 
return l

DEF getRoot (Self, the root: the TreeNode, l: List [int]):
IF the root: If the node exists #
l.append (root.val) # l is appended to the list of node values
self. getroot (root.left, l) # recursive
self.getroot (root.right, L)
the else:
return

Previous: list of intermediate node

Guess you like

Origin www.cnblogs.com/RiverMap/p/12584207.html