原题
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
解析
合并两个2叉树
给两个二叉树,合并的规则是:
如果两个树相同位置的节点存在,则将节点值相加作为新节点的值
如果该位置只有一棵树有节点,则将这个节点作为合并后的树相应位置的节点
Input:
Tree 1 Tree 2
1 2
/ /
3 2 1 3
/
5 4 7
Output:
Merged tree:
3
/
4 5
/
5 4 7
我的解法
public class Merge2BinaryTree {
public static TreeNode getMergedTree(TreeNode firstNode, TreeNode secondNode) {
if (firstNode == null && secondNode == null) {
return null;
}
TreeNode mergedTree = new TreeNode(0);
if (firstNode != null) {
mergedTree.setValue(mergedTree.getValue() + firstNode.getValue());
}
if (secondNode != null) {
mergedTree.setValue(mergedTree.getValue() + secondNode.getValue());
}
mergedTree.setLeftNode(
getMergedTree(firstNode == null ? null : firstNode.leftNode,
secondNode == null ? null : secondNode.leftNode));
mergedTree.setRightNode(
getMergedTree(firstNode == null ? null : firstNode.rightNode,
secondNode == null ? null : secondNode.rightNode));
return mergedTree;
}
}
/**
* 树的节点类,里面有该节点的值
* 以及左子节点,右子节点
*/
class TreeNode {
int value;
TreeNode leftNode;
TreeNode rightNode;
public TreeNode(int v) {
this.value = v;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public TreeNode getLeftNode() {
return leftNode;
}
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
public TreeNode getRightNode() {
return rightNode;
}
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
}
最优解
public class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return null;
int val = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val);
TreeNode newNode = new TreeNode(val);
newNode.left = mergeTrees(t1 == null ? null : t1.left, t2 == null ? null : t2.left);
newNode.right = mergeTrees(t1 == null ? null : t1.right, t2 == null ? null : t2.right);
return newNode;
}
}
思路其实一样,只是他用了三目表达式,减少了行数