本体正宗未看题解!本人自己写出来的!!!嘿嘿嘿
思路很简单,传入两个二叉树根节点,分别有三个细节判断:
第一:a二叉树为空,b二叉树不为空时,继续递归b二叉树
第二:a二叉树不为空,b二叉树为空,继续递归a二叉树
第三:全部为空,返回空节点
还有一个不算细节,是递归的必须条件,递归循环体
- package shuJuJieGouYuSuanFa.erChaShu;
-
-
- import java.util.LinkedList;
- import java.util.Queue;
-
- public class likou617 {
- public static void main(String[] args) {
- TreeNode r1 = new TreeNode(1);
- TreeNode r2 = new TreeNode(1);
- r1.left = new TreeNode(2);
- r1.left.left = new TreeNode(3);
- r2.right = new TreeNode(2);
- r2.right.right = new TreeNode(3);
- TreeNode t = new likou617().mergeTrees(r1, r2);
- // f1(t);
- f2(t);
- }
-
- private static void f2(TreeNode t) {
- Queue
dui = new LinkedList<>(); - int size = 0;
- TreeNode p = null;
- dui.offer(t);
- while (!dui.isEmpty()) {
- size = dui.size();
- for (int i = 0; i < size; i++) {
- p = dui.poll();
- System.out.print(p.val + " ");
- if (p.left != null) {
- dui.offer(p.left);
- }
- if (p.right != null) {
- dui.offer(p.right);
- }
- }
- System.out.println();
- }
- }
-
- private static void f1(TreeNode t) {
- if (t == null) {
- System.out.print("null ");
- return;
- }
- System.out.print(t.val + " ");
- f1(t.left);
- f1(t.right);
- }
-
- public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
- return dfs(root1, root2);
-
- }
-
- private TreeNode dfs(TreeNode root1, TreeNode root2) {
- TreeNode p = null;
- if (root1 == null && root2 != null) {
- p = new TreeNode(root2.val);
- p.left = dfs(root1, root2.left);
- p.right = dfs(root1, root2.right);
- return p;
- } else if (root1 != null && root2 == null) {
- p = new TreeNode(root1.val);
- p.left = dfs(root1.left, root2);
- p.right = dfs(root1.right, root2);
- return p;
- } else if (root1 == null && root2 == null) {
- return null;
- }
- p = new TreeNode(root1.val + root2.val);
- p.left = dfs(root1.left, root2.left);
- p.right = dfs(root1.right, root2.right);
- return p;
- }
- }
自己写出来还是挺有成就感的,嘿嘿嘿