Skip to content

Latest commit

 

History

History
50 lines (39 loc) · 1.38 KB

17.md

File metadata and controls

50 lines (39 loc) · 1.38 KB

【中规中矩】17. 合并二叉树 (递归)

解题思路

经典先序或后序递归即可。

代码

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if (!root1 && !root2) {
            return nullptr;
        } else if (!root1) {
            return root2;
        } else if (!root2) {
            return root1;
        }

        root1->left = mergeTrees(root1->left, root2->left);
        root1->right = mergeTrees(root1->right, root2->right);
        root1->val += root2->val;

        return root1;
    }
};
class Solution:
    def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
        if not root1 and not root2:
            return None
        elif not root1:
            return root2
        elif not root2:
            return root1
        
        root1.left = self.mergeTrees(root1.left, root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)
        root1.val += root2.val

        return root1

点我赞赏作者

github 题解

Image