递归岂是我这种凡人能懂的?
/**
* 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) {
if(root1==null)
{
return root2;
}
if(root2==null)
{
return root1;
}
TreeNode newNode=new TreeNode(root1.val+root2.val);
newNode.left=mergeTrees(root1.left,root2.left);
newNode.right=mergeTrees(root1.right,root2.right);
return newNode;
}
}
当root1为空的时候,新结点可以确定为root2了,反之root2为空新结点就是root1.
但是如果root1和root2都不为空,则创建一个新结点,值为root1和root2相加
以此类推,新结点的左子树就是当前root1的左子树再与当前root2的左子树进行处理
学习如逆水行舟,不进则退。和小吴一起加油吧!
|