题解 | #合并二叉树#
合并二叉树
https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
1:t1与t2是否为空,若为空则用另一个代替,若都为空,返回的值也是空。 2:前序遍历的特点,优先访问根节点,将两个根点的值相加创建到新树中。 3:两棵树再同时进入左子树和右子树。 /* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ function mergeTrees(t1, t2) { // write code here if (!t1) { return t2; } if (!t2) { return t1; } const node = new TreeNode(t1.val + t2.val); node.left = mergeTrees(t1.left, t2.left); node.right = mergeTrees(t1.right, t2.right); return node; } module.exports = { mergeTrees: mergeTrees, };