LeetCode Top100 合并二叉树
程序员文章站
2022-04-17 13:25:20
...
递归解法:
// 不修改原二叉树做法
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null || t2 == null)
return t1 == null ? t2 : t1;
// 不修改原二叉树做法
TreeNode res = new TreeNode(t1.val + t2.val);
res.left = mergeTrees(t1.left, t2.left);
res.right = mergeTrees(t1.right, t2.right);
return res;
}
}
//结果合并在t1上
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null || t2 == null)
return t1 == null ? t2 : t1;
t1.val += t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
}
非递归解法:用队列,一对一对的入队,如果左边为空,则把第二个树的子树直接赋给左边的树,下面就不管它
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return null;
if (t1 == null || t2 == null)
return t1 == null ? t2 : t1;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(t1);
queue.add(t2);
while (!queue.isEmpty()){
//出队
TreeNode l1 = queue.remove();
TreeNode l2 = queue.remove();
l1.val += l2.val;
if (l1.left == null){
l1.left = l2.left;
}
else if (l1.left != null && l2.left != null){
queue.offer(l1.left);
queue.offer(l2.left);
}
if (l2.right == null){
l1.right = l2.right;
}
else if (l1.right != null && l2.right != null){
queue.offer(l1.right);
queue.offer(l2.right);
}
}
return t1;
}
}
更加简洁的写法,队列里存大小为2的数组
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null)
return t2;
if (t2 == null)
return t1;
// use array in the queue to manipulate at the same time
Queue<TreeNode[]> queue = new LinkedList<>();
queue.offer(new TreeNode[]{t1,t2});
while (!queue.isEmpty()){
TreeNode[] nodes = queue.poll();
// merge 2 into 1 when it is not null
if (nodes[1] == null)
continue;
// nodes[0] must not be null
nodes[0].val += nodes[1].val;
// make sure nodes[0] will be null
if (nodes[0].left == null)
nodes[0].left = nodes[1].left;
else
queue.offer(new TreeNode[]{nodes[0].left,nodes[1].left});
if (nodes[0].right == null)
nodes[0].right = nodes[1].right;
else
queue.offer(new TreeNode[]{nodes[0].right,nodes[1].right});
}
return t1;
上一篇: 大数据从0到1构建
下一篇: 406. 根据身高重建队列
推荐阅读