问题描述:
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ \
4 5
/ \ \
5 4 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-binary-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
注意: 合并必须从两个树的根节点开始。
上代码,拿去即可运行:
package com.onlyqi.upup01.tree;
public class Node {
public Integer val;
public Node nodeLeft;
public Node nodeRight;
public Node() {
}
public Node(Integer val, Node nodeLeft, Node nodeRight) {
this.val = val;
this.nodeLeft = nodeLeft;
this.nodeRight = nodeRight;
}
public Node(Integer val) {
this.val = val;
}
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
public Node getNodeLeft() {
return nodeLeft;
}
public void setNodeLeft(Node nodeLeft) {
this.nodeLeft = nodeLeft;
}
public Node getNodeRight() {
return nodeRight;
}
public void setNodeRight(Node nodeRight) {
this.nodeRight = nodeRight;
}
}
package com.onlyqi.upup01.tree;
public class Test05 {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
node3.setNodeLeft(node5);
node1.setNodeLeft(node3);
node1.setNodeRight(node2);
Node tree1 = new Node(1);
Node tree2 = new Node(2);
Node tree3 = new Node(3);
Node tree4 = new Node(4);
Node tree7 = new Node(7);
tree1.setNodeRight(tree4);
tree3.setNodeRight(tree7);
tree2.setNodeLeft(tree1);
tree2.setNodeRight(tree3);
Node node= mergeTrees(node1,tree2);
PreOrderTraversal(node);
}
public static Node mergeTrees(Node t1, Node t2) {
if(t1==null && t2==null){
return null;
}
int x=t1==null?0:t1.val;
int y=t2==null?0:t2.val;
Node root=new Node(x+y);
root.setNodeLeft(mergeTrees(t1==null?null:t1.getNodeLeft(),t2==null?null:t2.getNodeLeft()));
root.setNodeRight(mergeTrees(t1==null?null:t1.getNodeRight(),t2==null?null:t2.getNodeRight()));
return root;
}
/*************先序遍历****************/
static void PreOrderTraversal(Node node) {
if (node != null) {
System.out.println(node.getVal()); // 打印根
PreOrderTraversal(node.getNodeLeft()); // 进入左子树
PreOrderTraversal(node.getNodeRight()); // 进入右子树
}
}
}
运行结果:
我要刷100道算法题,第86道