leetcode-1379-Find the same node in the cloned binary tree-medium

1379 Find the same node in the cloned binary tree
test question link
Title description

Give you two binary trees, the original tree original and the cloned tree cloned, and a target node located in the original tree original.

Among them, the cloned tree cloned is a copy of the original tree original.

Please find out the node that is the same as target in the cloned tree, and return a reference to that node (return the
node pointer in C/C++ and other languages ​​with pointers, and return the node itself in other languages).

note:

You cannot make changes to the two binary trees and the target node. Only references to existing nodes in the cloned tree can be returned.
Advanced: If nodes with the same value are allowed in the tree, how would you answer?

Example 1:

Input: tree = [7,4,3,null,null,6,19], target = 3 Output: 3

Example 2:

Input: tree = [7], target = 7 Output: 7

Example 3:

Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4

Example 4:

Input: tree = [1,2,3,4,5,6,7,8,9,10], target = 5 Output: 5

Example 5:

Input: tree = [1,2,null,3], target = 2 Output: 2

prompt:

The range of the number of nodes in the tree is [1, 10^4]. In the same tree, there is no node with the same value. The target node is
a node in the original tree , and will not be null.

Problem solving ideas

At the same time, the sequence traverses (bfs) original and cloned binary trees. When the target is found in the original, return to the node corresponding to the cloned tree at this time.

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* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
    
    
        queue<TreeNode*>q1;
        queue<TreeNode*>q2;

        q1.push(original);
        q2.push(cloned);
        while(!q1.empty()){
    
    
            TreeNode * tmp1 = q1.front();
            TreeNode * tmp2 = q2.front();
            q1.pop();
            q2.pop();

            if(tmp1 == target)
                return tmp2;
            
            if(tmp1->left){
    
    
                q1.push(tmp1->left);
                q2.push(tmp2->left);
            }
            if(tmp2->right){
    
    
                q1.push(tmp1->right);
                q2.push(tmp2->right);
            }
        }
        return NULL;
    }
};

Guess you like

Origin blog.csdn.net/Yang_1998/article/details/108547669