leetcode - 617. 合并二叉树
617. 合并二叉树
class Solution { //迭代 public TreeNode mergeTreesWithStack(TreeNode root1, TreeNode root2) { //如果当前root左右子树有一个是空的, 直接把非空的那个返回 if(root1 == null || root2 == null){ return root1 == null ? root2 : root1; } Stack<TreeNode> stack = new Stack<>(); stack.push(root1); stack.push(root2); while(!stack.isEmpty()){ //栈是先进后出的, 后加的2, 所以先出2 TreeNode cur2 = stack.pop(); TreeNode cur1 = stack.pop(); //直接把cur2的值累加到cur1上, 合并当前节点 cur1.val += cur2.val; //假如当前节点左右子树都有才能放到栈里 if(cur1.left != null && cur2.left != null){ stack.push(cur1.left); stack.push(cur2.left); }else if(cur1.left == null){ //如果有1为空, 把2非空的那个直接挂到1空的节点上 cur1.left = cur2.left; } if(cur1.right != null && cur2.right != null){ stack.push(cur1.right); stack.push(cur2.right); }else if(cur1.right == null){ cur1.right = cur2.right; } } return root1; } //递归 public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { //如果1为空, 直接返回直接2非空的那个, 挂到root1上 if(root1 == null){ return root2; } //如果2为空, 直接返回root1, 没节点挂到root1上, 还是原来的节点 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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理