刷题笔记|leetcode.617.Merge Two Binary Trees

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.
【刷题笔记|leetcode.617.Merge Two Binary Trees】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 1Tree 2 12 / \/ \ 3213 /\\ 547 Output: Merged tree: 3 / \ 45 / \\ 547

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; } } };

    推荐阅读