LeetCode 617. Merge Two Binary Trees 自我反思

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.、

一开始遇到一个小问题,总是在想,有返回值怎么递归,递归的貌似一般都是没有返回值的,后来知道,这更像是链表的拼接,还有忘了怎么直接生成一个新的链表,要用pointer 指向 在new一个结构体,还有递归的时候先考虑返回条件,这个要想清楚。算是重新开始吧。

/**
 * 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;
        if(t2 == NULL)
            return t1;
        
        TreeNode *temp = new TreeNode(t1->val + t2->val);
        temp->left = mergeTrees(t1->left, t2->left);
        temp->right = mergeTrees(t1->right, t2->right);
        return temp;
            
    }
};

猜你喜欢

转载自blog.csdn.net/tzy3013218117/article/details/80848584