题目描述
分析
利用中序遍历的性质,遍历两棵树所有节点,存到两个数组中
再利用归并排序进行合并
这样做的优势在于可以节省空间和时间复杂度
算法
中序遍历,归并排序
过程
首先通过中序遍历,构建两个升序数组
利用归并排序进行合并(此处实际上就是多遍历一遍两棵树)
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {number[]}
*/
var getAllElements = function (root1, root2) {
const arr1 = []
const arr2 = []
const ret = []
inOrder(arr1, root1)
inOrder(arr2, root2)
let p1 = 0,
p2 = 0
while (p1 < arr1.length || p2 < arr2.length) {
if (p2 >= arr2.length || (p1 < arr1.length && arr1[p1] <= arr2[p2])) {
ret.push(arr1[p1++])
} else {
ret.push(arr2[p2++])
}
}
return ret
}
function inOrder(arr, root) {
if (!root) return
if (root.left) inOrder(arr, root.left)
arr.push(root.val)
if (root.right) inOrder(arr, root.right)
}