LeetCode 617 The LeetCode Road of Merging Binary Tree HERODING

Given two binary trees, imagine that when you overlay one of them on the other, some nodes of the two binary trees will overlap.

You need to merge them into a new binary tree. The rule of merging is that if two nodes overlap, their values ​​are added as the new value after the node is merged, otherwise the node that is not NULL will be directly used as the node of the new binary tree.

Insert picture description here

Note: The merge must start from the root node of the two trees.

Problem-solving idea:
The easiest way to combine two binary trees into one is to construct a binary tree with nothing, and then insert the two existing binary trees into it. The idea of ​​recursion can be used when recursive later. , Pay attention to the judgment, if the node is null, then the left and right subtrees must not exist, and the recursion cannot be continued, so a judgment must be made. The code is as follows:

/**
 * 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 && !t2){
    
    
            return NULL;
        }
        TreeNode * root = new TreeNode(0);
        if(t1){
    
    
            root->val += t1->val;
        }
        if(t2){
    
    
            root->val += t2->val;
        }
        // 注意这里的判断
        root->left = mergeTrees(t1?t1->left:NULL, t2?t2->left:NULL);
        root->right = mergeTrees(t1?t1->right:NULL, t2?t2->right:NULL);
        return root;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108745170