合并二叉树
/**
* 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) {
//如果树1节点是null ,返回树2节点
if(root1==null){
return root2;
}
//如果树2节点是null ,返回树1节点
if(root2==null){
return root1;
}
//这边处理两个节点都有值的情况
//新建节点sum 值为 相加和
TreeNode sum = new TreeNode(root1.val + root2.val);
//这边进入遍历递归,每次处理一个节点都要处理其左右两个子节点
sum.left = mergeTrees(root1.left,root2.left);
sum.right = mergeTrees(root1.right,root2.right);
return sum;
}
}
填充每个节点的下一个右侧节点
class Solution {
public Node connect(Node root) {
if (root == null) {
return root;
}
// 从根节点开始
Node leftmost = root;
while (leftmost.left != null) {
// 遍历这一层节点组织成的链表,为下一层的节点更新 next 指针
Node head = leftmost;
while (head != null) {
// CONNECTION 1
head.left.next = head.right;
// CONNECTION 2
if (head.next != null) {
head.right.next = head.next.left;
}
// 指针向后移动
head = head.next;
}
// 去下一层的最左的节点
leftmost = leftmost.left;
}
return root;
}
}