zoukankan      html  css  js  c++  java
  • 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

    上一篇:链表的中间结点

  • 相关阅读:
    29 求和
    28 跳转控制语句 goto
    27 跳转控制语句 continue
    26 跳转控制语句 break
    25 打印金字塔
    24 打印九九乘法表
    23 多重循环控制
    22 do-while 循环
    21 while 循环
    20 for循环控制
  • 原文地址:https://www.cnblogs.com/RiverMap/p/12584207.html
Copyright © 2011-2022 走看看