本文主要是介绍代码随想录——合并二叉树(Leetcode617),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接
层序遍历
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {if(root1 == null){return root2;}if(root2 == null){return root1;}Deque<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root1);queue.offer(root2);while(!queue.isEmpty()){TreeNode node1 = queue.poll();TreeNode node2 = queue.poll();node1.val += node2.val;if(node1.left != null && node2.left != null){queue.offer(node1.left);queue.offer(node2.left);}if(node1.right != null && node2.right != null){queue.offer(node1.right);queue.offer(node2.right);}if(node1.left == null && node2.left != null){node1.left = node2.left;}if(node1.right == null && node2.right != null){node1.right = node2.right;}}return root1;}
}
这篇关于代码随想录——合并二叉树(Leetcode617)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!