【leetcode 1305. 两棵二叉搜索树中的所有元素】Python 解题思路

题目链接:

给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。

方法1:先序遍历(或者其他方式)+sort 排序

# Definition for a binary tree node.
# 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]:
        ans=[]
        def dfs(root):
            nonlocal ans
            if root:
                ans.append(root.val)
                dfs(root.left)
                dfs(root.right)
        dfs(root1)
        dfs(root2)
        ans.sort()
        return ans

方法2:中序遍历 + 归并排序 (方法2比方法1还慢)

# Definition for a binary tree node.
# 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]:       
        def dfs(root):
            nonlocal ans
            if root:               
                dfs(root.left)
                ans.append(root.val)
                dfs(root.right)
            else:
                return
        ans=[]
        dfs(root1)
        list1=ans
        ans=[]
        dfs(root2)
        list2=ans
        stack=[]
        i=0
        j=0
        while i<len(list1) and j<len(list2):
            if list1[i]<list2[j]:
                stack.append(list1[i])
                i=i+1
            elif list1[i]>list2[j]:
                stack.append(list2[j])
                j=j+1
            else:
                stack.append(list2[j])
                stack.append(list1[i])
                i=i+1
                j=j+1
        if i==len(list1) and j!=len(list2):
            stack=stack+list2[j:]
        elif i!=len(list1) and j==len(list2):
            stack=stack+list1[i:]
        return stack
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值