LeetCode-两棵二叉搜索树的所有元素

时间:2020-03-27
本文章向大家介绍LeetCode-两棵二叉搜索树的所有元素,主要包括LeetCode-两棵二叉搜索树的所有元素使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

注:LeetCode--树专题。

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

题目描述:

给你 root1 和 root2 这两棵二叉搜索树。

请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.

示例:

输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]

....

解题思路:

关于二叉树,我的第一想法就是递归。根据题目要求,很明显就是要遍历二叉树的各个节点,获取该节点的值,并将它们排序。

代码:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
l = []
self.getroot(root1, l) # 获取root1中的各个节点的值
self.getroot(root2, l) # 获取root2中的各个节点的值
        l.sort()
return l

def getroot(self, root: TreeNode, l: List[int]):
if root: # 如果节点存在
l.append(root.val) # 将节点值追加到 l 列表中
self.getroot(root.left, l) # 递归
self.getroot(root.right, l)
else:
return

上一篇:链表的中间结点

原文地址:https://www.cnblogs.com/RiverMap/p/12584207.html