JavaScript题解 | #合并二叉树#
合并二叉树
https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ function mergeTrees(t1, t2) { if(!t1) { return t2; } else if (!t2) { return t1; } else if (!t1 && !t2) { return null; } const val = t1.val + t2.val; let node = new TreeNode(val); node.left = mergeTrees(t1.left, t2.left); node.right = mergeTrees(t1.right, t2.right); return node; } module.exports = { mergeTrees, };
思路:
对于一个节点
node = { val: t1 && t2 都存在时, val = t1.val + t2.val; 都不存在时为null,只有一个时为存在的那个, left: mergeTreeNode(t1.left, t2.left), right: mergeTreeNode(t1.right, t2.right) }
递归完成两棵树所有的节点