From 1dd57ca07df04e6d9af8ec4067447651d9433de9 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:19:18 +0800 Subject: [PATCH] =?UTF-8?q?Update=200617.=E5=90=88=E5=B9=B6=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0617.合并二叉树 Java版本 --- problems/0617.合并二叉树.md | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index adc0703b..520a7384 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -256,7 +256,60 @@ public: Java: +```Java +class Solution { + // 递归 + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + root1.val += root2.val; + root1.left = mergeTrees(root1.left, root2.left); + root1.right = mergeTrees(root1.right, root2.right); + return root1; + } +} +class Solution { + // 迭代 + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + Stack stack = new Stack<>(); + stack.push(root2); + stack.push(root1); + while (!stack.isEmpty()) { + TreeNode node1 = stack.pop(); + TreeNode node2 = stack.pop(); + node1.val += node2.val; + if (node2.right != null && node1.right != null) { + stack.push(node2.right); + stack.push(node1.right); + } else { + if (node1.right == null) { + node1.right = node2.right; + } + } + if (node2.left != null && node1.left != null) { + stack.push(node2.left); + stack.push(node1.left); + } else { + if (node1.left == null) { + node1.left = node2.left; + } + } + } + return root1; + } +} +``` Python: