617. Merge Two Binary Trees(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/82721112

题目:

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.
这里写图片描述

解释:
将两个二叉树融合,如果相同位置都有值就相加,如果一个有一个没有,返回有值的结点值。
python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if (t1==None):
            return t2
        elif(t2==None):
            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==NULL)
            return t2;
        else if(t2==NULL)
            return t1;
        else
        {
            TreeNode *node=new TreeNode(t1->val+t2->val);
            node->left=mergeTrees(t1->left, t2->left);
            node->right=mergeTrees(t1->right,t2->right);
            return node;
        }
        
    }
};

总结:
学到了cpp是如何表示一棵树的。。。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/82721112
今日推荐