617.合并二叉树
思路
简单的递归,判断两个节点分别为空的情况即可,这里将1树构造为最终结果。
应该使用两个队列来进行层序遍历也比较简单,代码稍微麻烦一些,要多增加几个判断语句。
代码
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1==null) {
root1=root2;
return 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;
}
class Solution {
// 使用队列迭代
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) return root2;
if (root2 ==null) return root1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root1);
queue.offer(root2);
while (!queue.isEmpty()) {
TreeNode node1 = queue.poll();
TreeNode node2 = queue.poll();
// 此时两个节点一定不为空,val相加
node1.val = 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);
}
// 若node1的左节点为空,直接赋值
if (node1.left == null && node2.left != null) {
node1.left = node2.left;
}
// 若node1的右节点为空,直接赋值
if (node1.right == null && node2.right != null) {
node1.right = node2.right;
}
}
return root1;
}
}
700.二叉搜索树中的搜索
思路
二叉搜索树常规解法,while循环来迭代进行root的查找操作。
递归也可以做。
比较简单
代码
public TreeNode searchBST(TreeNode root, int val) {
while (root!=null && root.val!=val ){
if (root.val<val) root=root.right;
else root=root.left;
}
return root;
}