题目地址https://leetcode-cn.com/problems/merge-two-binary-trees/java
递归的话咱们首先须要递归的终止条件,对于本题而言,递归的终止条件是t1和t2递归到任意一方为null的状况,由于这种条件下,咱们不须要继续合并下去,直接返回不为null那一方便可。总体递归的过程就比较简单了,分为三个步骤git
算法总体的时间复杂度为O(n) 空间复杂度为O(h) 其中h为二叉树的最大深度github
var mergeTrees = function(t1, t2) { if (t1 == null) return t2; if (t2 == null) return t1; const newRoot = new TreeNode(t1.val + t2.val); newRoot.left = mergeTrees(t1.left, t2.left); newRoot.right = mergeTrees(t1.right, t2.right); return newRoot; };
这种解法以t1为基准,直接在t1上面操做,最终将t1返回。时间复杂度O(n) 空间复杂度O(n)。算法
var mergeTrees = function(t1, t2) { if (t1 === null) return t2; if (t2 === null) return t1; const stack = [[t1, t2]]; while (stack.length > 0) { let [a, b] = stack.pop(); // 若是b为null,那不管a是否为空,a都不须要作出改变 if (b === null) continue; a.val = a.val + b.val; // 下面处理a和b的子节点 // 若是a的左孩子或者右孩子为null,那直接将其赋值为b的左孩子或者右孩子 if (a.left === null) a.left = b.left; else stack.push([a.left, b.left]) if (a.right === null) a.right = b.right else stack.push([a.right, b.right]) } return t1; };
这里基本上是和DFS同样,由于不须要在乎遍历的顺序,只须要将每一个节点都遍历到,所以也可使用BFS。时间复杂度O(n) 空间复杂度O(n)。数据结构
class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { Queue<TreeNode[]> queue = new LinkedList<>(); if (t1 == null) return t2; if (t2 == null) return t1; queue.offer(new TreeNode[]{t1, t2}); while (!queue.isEmpty()) { TreeNode[] t = queue.poll(); if (t[1] == null) continue; t[0].val += t[1].val; if (t[0].left == null) t[0].left = t[1].left; else queue.offer(new TreeNode[]{t[0].left, t[1].left}); if (t[0].right == null) t[0].right = t[1].right; else queue.offer(new TreeNode[]{t[0].right, t[1].right}); } return t1; } }
更多LeetCode题解和数据结构方面的内容,能够关注个人github,求个star~ ▄█▔▉●code