LeetCode每日一题(15)——两棵二叉搜索树中的所有元素

简介: 两棵二叉搜索树中的所有元素1.题目2.示例3.思路4.代码

1.题目


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


2.示例


示例 1:


11.png


输入:root1 = [2,1,4], root2 = [1,0,3]

输出:[0,1,1,2,3,4]


示例 2:


13.png


输入:root1 = [1,null,8], root2 = [8,1]

输出:[1,1,8,8]


提示:


每棵树的节点数在 [0, 5000] 范围内

-105 <= Node.val <= 105


3.思路


用二叉树,升序选择前序遍历,两个树的话可以分别排序存数组,再比较两个数组的最小值,将最小值依次加入答案数组


4.代码


/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
//将二叉树中序遍历,获得排序好的数组
func inorder(root *TreeNode) (res []int) {
  var dfs func(*TreeNode)
  dfs = func(node *TreeNode) {
    if node == nil {
      return
    }
    dfs(node.Left)
    res = append(res, node.Val)
    dfs(node.Right)
  }
  dfs(root)
  return
}
func getAllElements(root1, root2 *TreeNode) []int {
  //用上面的方法得到两个排序后的数组
  nums1 := inorder(root1)
  nums2 := inorder(root2)
  p1, n1 := 0, len(nums1)
  p2, n2 := 0, len(nums2)
  //遍历两个数组,按顺序合成一个数组
  ans := make([]int, 0, n1+n2)
  for {
    //如果nums1的数据已经全部加入ans数组,则把nums2剩余的数字加入ans
    //数组组合完成,返回答案
    if p1 == n1 {
      return append(ans, nums2[p2:]...)
    }
    if p2 == n2 {
      return append(ans, nums1[p1:]...)
    }
    if nums1[p1] < nums2[p2] {
      ans = append(ans, nums1[p1])
      p1++
    } else {
      ans = append(ans, nums2[p2])
      p2++
    }
  }
}
相关文章
|
6天前
【力扣】-- 移除链表元素
【力扣】-- 移除链表元素
16 1
|
12天前
【LeetCode 27】347.前k个高频元素
【LeetCode 27】347.前k个高频元素
23 0
|
12天前
【LeetCode 45】701.二叉搜索树中的插入操作
【LeetCode 45】701.二叉搜索树中的插入操作
8 1
|
12天前
【LeetCode 44】235.二叉搜索树的最近公共祖先
【LeetCode 44】235.二叉搜索树的最近公共祖先
11 1
|
12天前
【LeetCode 48】108.将有序数组转换为二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
26 0
|
12天前
【LeetCode 47】669.修剪二叉搜索树
【LeetCode 47】669.修剪二叉搜索树
7 0
|
12天前
【LeetCode 46】450.删除二叉搜索树的节点
【LeetCode 46】450.删除二叉搜索树的节点
9 0
|
12天前
【LeetCode 42】501.二叉搜索树中的众数
【LeetCode 42】501.二叉搜索树中的众数
7 0
|
12天前
【LeetCode 41】530.二叉搜索树的最小绝对差
【LeetCode 41】530.二叉搜索树的最小绝对差
7 0
|
12天前
【LeetCode 40】98.验证二叉搜索树
【LeetCode 40】98.验证二叉搜索树
8 0