[路飞]_两棵二叉搜索树中的所有元素

167 阅读1分钟

1305. 两棵二叉搜索树中的所有元素

题目

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

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

示例1

image.png

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

前言

就,离谱。刚完成链表排序;脑子还是懵懵的,链表,排序,链表都能拿来排序;现在让我对二叉树排序;这,可真的看的起我的水平呀,下次不会让我对图排序吧?不会不会,图怎么能排序呢?

题解

中序遍历+合并

对于搜索二叉树,中序遍历搜索二叉树可以得到递增的数组;将root1root2分别中序遍历得到递增数组list1,list2;合并list1和list2即可

代码

var getAllElements = function (root1, root2) {
  const list1 = []
  const list2 = []
  helper(root1, list1)
  helper(root2, list2)
  let result = []
  while (list1.length || list2.length) {
    const s1 = list1[0]
    const s2 = list2[0]
    if (s1 !== undefined && s2 !== undefined) {
      if (s1 < s2) {
        result.push(list1.shift())
      } else {
        result.push(list2.shift())
      }
    } else if (s1 === undefined) {
      result.push(list2.shift())
    } else {
      result.push(list1.shift())
    }
  }
  return result
  function helper(node, path) {
    if (node === null) return null
    helper(node.left, path)
    path.push(node.val)
    helper(node.right, path)
  }
}

结语

我错了,刚看到题目一位很难,实际解决的时候发现难度一般啊;哈哈,心情舒畅;继续搞