Merge Two Binary Trees

来源:互联网 发布:惠州市博罗县网络问政 编辑:程序博客网 时间:2024/05/16 20:29

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.
Note: The merging process must start from the root nodes of both trees.

合并二叉树,我先去补一下二叉树的知识…
二叉树的操作总与递归相关,我还不是很熟练
但是总理思路是同时遍历两棵树,同一位置两个元素都非空则相加,有且仅有一个为空则将为空的节点记为0,两个都为空则新树该节点也为空,该位置的左右节点进行递归

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def mergeTrees(self, t1, t2):        """        :type t1: TreeNode        :type t2: TreeNode        :rtype: TreeNode        """        if not t1 and not t2:            return None        elif not t1 and t2:            return t2        elif t1 and not t2:            return t1        else:            node = TreeNode(t1.val + t2.val)            node.left = self.mergeTrees(t1.left, t2.left)            node.right = self.mergeTrees(t1.right, t2.right)            return node

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