递归方案:
非递归方案:
class Solution {
/**
* 将两个树的对应节点捆绑起来,如果某一个节点在树1中空,而在树2中为非空则直接将 该节点赋值给树1
*/
static class Entry {
public Entry(TreeNode tree1, TreeNode tree2) {
this.tree1 = tree1;
this.tree2 = tree2;
}
public TreeNode tree1;
public TreeNode tree2;
}
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (Objects.isNull(t1)) {
return t2;
} else if (Objects.isNull(t2)) {
return t1;
}
Entry en = new Entry(t1, t2);
Stack<Entry> s = new Stack<>();
s.push(en);
while (!s.isEmpty()) {
en = s.pop();
//
if (Objects.isNull(en.tree1) || Objects.isNull(en.tree2)) {
continue;
}
en.tree1.val = en.tree1.val + en.tree2.val;
//如果tree1树为空的话直接将树2该节点赋值给树1中即可,然后忽略继续处理
if (en.tree1.left == null) {
en.tree1.left = en.tree2.left;
} else {
s.push(new Entry(en.tree1.left, en.tree2.left));
}
if (en.tree1.right == null) {
en.tree1.right = en.tree2.right;
} else {
s.push(new Entry(en.tree1.right, en.tree2.right));
}
}
return t1;
}
}