解法一:深度优先遍历二叉树
1、深度优先遍历二叉树
2、如果值为整数,则放入数组中
3、对数组排序
/**
* 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 list = [];
function dfs(root) {
if (root) {
list.push(root.val);
dfs(root.left);
dfs(root.right);
}
}
dfs(root1);
dfs(root2);
return list.sort((a, b) => a - b);
};
解法二:中序遍历 + 归并排序
先对二叉树中序遍历,得到两个有序数组,然后依次从两个数组头部取较小的数,最后得到一个升序数组。
/**
* 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 res = [];
const list1 = [];
const list2 = [];
inorder(root1, list1);
inorder(root2, list2);
let i = 0,
j = 0;
while (i < list1.length && j < list2.length) {
if (list1[i] < list2[j]) {
res.push(list1[i]);
i++;
} else {
res.push(list2[j]);
j++;
}
}
if (i === list1.length) {
res.push(...list2.splice(j));
}
if (j === list2.length) {
res.push(...list1.splice(i));
}
return res;
};
function inorder(root, list) {
if (root) {
inorder(root.left, list);
list.push(root.val);
inorder(root.right, list);
}
}