image.png

解题思路

递归

image.png

  1. public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
  2. if (t1 == null)
  3. return t2;
  4. if (t2 == null)
  5. return t1;
  6. t1.val += t2.val;
  7. t1.left = mergeTrees(t1.left, t2.left);
  8. t1.right = mergeTrees(t1.right, t2.right);
  9. return t1;
  10. }

迭代

image.png

  1. public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
  2. if (t1 == null)
  3. return t2;
  4. Stack < TreeNode[] > stack = new Stack < > ();
  5. stack.push(new TreeNode[] {t1, t2});
  6. while (!stack.isEmpty()) {
  7. TreeNode[] t = stack.pop();
  8. if (t[0] == null || t[1] == null) {
  9. continue;
  10. }
  11. t[0].val += t[1].val;
  12. if (t[0].left == null) {
  13. t[0].left = t[1].left;
  14. } else {
  15. stack.push(new TreeNode[] {t[0].left, t[1].left});
  16. }
  17. if (t[0].right == null) {
  18. t[0].right = t[1].right;
  19. } else {
  20. stack.push(new TreeNode[] {t[0].right, t[1].right});
  21. }
  22. }
  23. return t1;
  24. }