Nothing to brush LetCode - 617. Merge binary tree

CSDN Topic Challenge Phase 2
Participation Topic: Algorithm Solution

1. Description of the topic

You are given two binary trees: root1 and root2.

Imagine that when you overlay one tree on top of the other, some nodes on both trees will overlap (and others won't). You need to merge these two trees into a new binary tree. The rule of merging is: if two nodes overlap, then add the values ​​of these two nodes as the new value of the merged node; otherwise, the node that is not null will be directly used as the node of the new binary tree.

Returns the merged binary tree.

Note: The merging process must start from the root node of both trees.
insert image description here

输入:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
输出:[3,4,5,5,4,null,7]

2. Topic link

617. Merge Binary Trees

3. Idea explanation

We need to use dfs or bfs to search the binary tree. There are three situations in the search process

1. One tree node is empty, and the other tree node is not empty. At this time, directly assign another tree node.
2. Both tree nodes are not empty, and the values ​​are merged at this time.
3. Both tree nodes are empty, no processing is done.

4. Template code

back to new tree

TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
    
    
	// 如果有一个节点为空,则直接赋值另一个节点,对应情况1,3
    if (root1 == nullptr) {
    
    
        return root2;
    }
    if (root2 == nullptr) {
    
    
        return root1;
    }
    // 新建一棵树,首先处理头节点
    TreeNode* merged = new TreeNode(root1->val + root2->val);
    // 然后递归处理左右节点
    merged->left = mergeTrees(root1->left, root2->left);
    merged->right = mergeTrees(root1->right, root2->right);
    return merged;
}

Make changes on the original tree

TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
    
    
    if (root1 == nullptr) {
    
    
        return root2;
    }
    if (root2 == nullptr) {
    
    
        return root1;
    }
    root1->val = root1->val + root2->val;
    root1->left = mergeTrees(root1->left, root2->left);
    root1->right = mergeTrees(root1->right, root2->right);
    return root1;
}

Guess you like

Origin blog.csdn.net/REstrat/article/details/126928878