方法一:
递归,前序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//前序遍历
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
//根操作
if(t1 == null) return t2;
if(t2 == null) return t1;
t1.val +=t2.val;
//左
t1.left = mergeTrees(t1.left,t2.left);
//右
t1.right = mergeTrees(t1.right,t2.right);
return t1;
}
}
还可以创建一个全新的树
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return null;
if (t1 == null) return t2;
if (t2 == null) return t1;
TreeNode root = new TreeNode(t1.val + t2.val);
root.left = mergeTrees(t1.left, t2.left);
root.right = mergeTrees(t1.right, t2.right);
return root;
}
方法二:
非递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//非递归
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null)return t2;
Stack < TreeNode[] > stack = new Stack < > ();
stack.push(new TreeNode[] {t1, t2});
while(!stack.isEmpty()){
TreeNode [] node = stack.pop();
//如果当前 t1或者t2结点为空结点,则不做操作
if(node[0] == null || node[1] == null) continue;
node[0].val += node[1].val;
if(node[0].left == null){
node[0].left = node[1].left;
}
else{
stack.push(new TreeNode[]{node[0].left,node[1].left});
}
if(node[0].right == null){
node[0].right = node[1].right;
}
else{
stack.push(new TreeNode[]{node[0].right,node[1].right});
}
}
return t1;
}
}