• 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

    上一篇:链表的中间结点

  • 相关阅读:
    win7与centos虚拟机的共享文件夹创建
    MySQL视图
    MySQL分区表与合并表
    PHP读写XML文件的四种方法
    备份与恢复
    MySQL日志
    MySQL锁问题
    优化数据库对象
    ActiveReport资料
    对ArrayList 进行深拷贝
  • 原文地址:https://www.cnblogs.com/RiverMap/p/12584207.html
Copyright © 2020-2023  润新知