617. 合并二叉树

617. 合并二叉树

原题

/**
 * 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) {
        return dfs(root1,root2);
    }

    //深度优先遍历,将root2拷贝到root1进行返回
    public TreeNode dfs(TreeNode root1,TreeNode root2){
        if(root1==null&&root2==null){
            return null;
        }
        if(root1==null){
            return root2;
        }
        if(root2==null){
            return root1;
        }
        //更新root1的值
        root1.val=root1.val+root2.val;
        //遍历root1左子树
        root1.left = dfs(root1.left,root2.left);
        //遍历root1右子树
        root1.right = dfs(root1.right,root2.right);
        //返回root1
        return root1;

    }
}

你可能感兴趣的:(LeetCode刷题,深度优先,算法)