AlgoDaily Solution

1var assert = require('assert');
2
3function Node(val) {
4 this.val = val;
5 this.left = this.right = null;
6}
7
8function mergeTwoBinaryTrees(tree1, tree2) {
9 if (tree1 == null) {
10 return tree2;
11 }
12 if (tree2 == null) {
13 return tree1;
14 }
15 tree1.val += tree2.val;
16 tree1.left = mergeTwoBinaryTrees(tree1.left, tree2.left);
17 tree1.right = mergeTwoBinaryTrees(tree1.right, tree2.right);
18 return tree1;
19}
20
21function Node(val) {
22 this.val = val;
23 this.left = null;
24 this.right = null;
25}
26
27// Regular binary trees
28var tree1 = new Node(4);
29tree1.left = new Node(1);
30tree1.right = new Node(3);
31
32var tree2 = new Node(5);
33tree2.left = new Node(10);
34tree2.left.left = new Node(17);
35tree2.left.right = new Node(3);
36tree2.right = new Node(8);
37
38// Binary search trees
39var tree3 = new Node(6);
40tree3.left = new Node(3);
41
42var tree4 = new Node(5);
43tree4.left = new Node(3);
44tree4.left.left = new Node(2);
45tree4.left.left.left = new Node(1);
46
47var tree5 = new Node(8);
48tree5.left = new Node(6);
49tree5.right = new Node(9);
50tree5.left.left = new Node(5);
51tree5.left.right = new Node(7);
52tree5.right.right = new Node(10);
53
54try {
55 assertIsFunction(
56 mergeTwoBinaryTrees,
57 '`mergeTwoBinaryTrees` should be a function'
58 );
59
60 console.log('PASSED: ' + '`mergeTwoBinaryTrees` should be a function');
61} catch (err) {
62 console.log(err);
63}
64
65try {
66 var presetMerged = mergeTwoBinaryTrees(tree1, tree2);
67 var mergedTree = new Node(9);
68 mergedTree.left = new Node(11);
69 mergedTree.left.left = new Node(17);
70 mergedTree.left.right = new Node(3);
71 mergedTree.right = new Node(11);
72 assert.deepEqual(presetMerged, mergedTree);
73
74 console.log(
75 'PASSED: `mergeTwoBinaryTrees(tree1, tree2)` should return a merged tree'
76 );
77} catch (err) {
78 console.log(err);
79}
80
81function assertIsFunction(f) {
82 return typeof f === 'function';
83}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
76
var assert = require('assert');
function Node(val) {
this.val = val;
this.left = this.right = null;
}
function mergeTwoBinaryTrees(tree1, tree2) {
// Fill in this method
return tree1;
}
function Node(val) {
this.val = val;
this.left = null;
this.right = null;
}
// Regular binary trees
var tree1 = new Node(4);
tree1.left = new Node(1);
tree1.right = new Node(3);
var tree2 = new Node(5);
tree2.left = new Node(10);
tree2.left.left = new Node(17);
tree2.left.right = new Node(3);
OUTPUT
Results will appear here.