[LeetCode] 617. Merge Two Binary Trees

来源:互联网 发布:最伟大的意大利人知乎 编辑:程序博客网 时间:2024/06/05 14:21

Problem :

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.

Example 1:

Input: Tree 1                     Tree 2                            1                         2                                      / \                       / \                                    3   2                     1   3                               /                           \   \                            5                             4   7                  Output: Merged tree:     3    / \   4   5  / \   \  5   4   7

Note: The merging process must start from the root nodes of both trees.


解题思路:构造树的问题很容易联想到用分治法来解决,这道题的特殊之处在于,每构造一个节点需要考虑四种情况:

1. 两子树节点均为空

2. t1节点为空,t2节点不为空

3. t1节点不为空,t2节点为空

4. 两子树节点均不为空

递归简单求解:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {        return mergeEachNode(t1, t2);    }        // 分四种情况合并每个树节点    TreeNode* mergeEachNode(TreeNode* t1, TreeNode* t2) {        TreeNode* root = NULL;        if (t1 == NULL && t2 == NULL) return NULL;        if (t1 != NULL && t2 == NULL) {            root = new TreeNode(t1->val);            root->left = mergeEachNode(t1->left, NULL);            root->right = mergeEachNode(t1->right, NULL);        }        if (t1 == NULL && t2 != NULL) {            root = new TreeNode(t2->val);            root->left = mergeEachNode(t2->left, NULL);            root->right = mergeEachNode(t2->right, NULL);        }        if (t1 != NULL && t2 != NULL) {            root = new TreeNode(t1->val + t2->val);            root->left = mergeEachNode(t1->left, t2->left);            root->right = mergeEachNode(t1->right, t2->right);        }        return root;    }};


原创粉丝点击