leetcode.617.Merge Two Binary Trees

来源:互联网 发布:单片机最小系统的组成 编辑:程序博客网 时间:2024/05/17 07:39

Description

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

sln

阅读完题目之后分析的结果是,在这个树融合的过程中,每个位置上的节点的融合相对于其他位置的节点而言是独立的,也就是说我只要便利每一个位置,将这个位置上两棵树的节点融合就可以了,不用管其他任何事情。
那么要遍历这两棵树的方法有前序,中序和后序。但由于我们这里并不需要输出每个节点的值,所以用哪个顺序关系并不大,只是要借鉴这几种遍历方法的递归思想而已。当我们拿到当前位置时,我们首先考虑当前位置的两个节点是否需要融合,即如果两个节点都非空则需要融合。如果不需要融合,那么我们只需要返回非空的那个节点即可。如果需要融合,那么融合后得到新节点的val我们是很容易确定的,通过相加即可。新节点的左右节点的融合呢,同样交给这个mergeTree的函数来完成,在确定了新节点的val后,这个融合问题就可以看作t1和t2当前位置节点的左子树融合以及右子树融合的问题啦。c++实现如下

/** * 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) {        if (t1 == NULL) {            return t2;        } else if (t2 == NULL) {            return t1;        } else {            TreeNode* newNode = new TreeNode(t1->val + t2->val);            newNode->left = mergeTrees(t1->left, t2->left);            newNode->right = mergeTrees(t1->right, t2->right);            return newNode;        }    }};
原创粉丝点击