Leetcode-1379-找出克隆二叉树中的相同节点-c++

题目详见https://leetcode.cn/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/

DFS题解

cpp 复制代码
class Solution {
public:
    TreeNode *getTargetCopy(TreeNode *original, TreeNode *cloned, TreeNode *target) {
        if (original == nullptr) {	// 遍历完original还没找到返回空指针
            return nullptr;
        }
        if (original == target) {	// 在original中找到了目标节点
            return cloned;
        }
        // DFS就是按照中序遍历走到底
        TreeNode *left = getTargetCopy(original->left, cloned->left, target);	// 先向左(同步1)
        if (left != nullptr) {	// 向左走到底
            return left;
        }
        return getTargetCopy(original->right, cloned->right, target);	// 再向右(同步2)
    }
};
  • 注意代码块中的 同步1 和 同步2,
  • 这里可以看到original向左走,cloned也向左走。original向右走,cloned也向右走。
  • 因此当条件if(original ==target)达成的时候,original位置和cloned的位置也在一个位置,因此直接返回cloned当前节点就行。

BFS题解

官方题解如下,下面将几个关键的点和代码配对起来

使用队列同时对二叉树original和cloned进行广度优先搜索,初始时分别将根节点original和cloned压入队列q1和q2 (1) 。假设当前搜索的节点分别为node1与node2,将node1与node2分别弹出队列***(2),如果node1节点的引用等于target节点的引用,那么返回node2,否则分别将node1与node2的非空子节点压入队列q1和q2,继续搜索过程(3)***。

cpp 复制代码
class Solution {
public:
    TreeNode *getTargetCopy(TreeNode *original, TreeNode *cloned, TreeNode *target) {
        queue<TreeNode *> q1, q2;
        // (1)
        q1.push(original);
        q2.push(cloned);
        while (!q1.empty()) {
        	// (2).1 取但未弹,还有
            TreeNode *node1 = q1.front(), *node2 = q2.front();
            // (2).2 弹,没了
            q1.pop();
            q2.pop();
            if (node1 == target) {
                return node2;
            }
            // (3)
            if (node1->left != nullptr) {	// 先压左
                q1.push(node1->left);
                q2.push(node2->left);
            }
            if (node1->right != nullptr) {	// 再压右
                q1.push(node1->right);
                q2.push(node2->right);
            }
        }
        return nullptr; // impossible case
    }
};

笔者也在新手学习期中,所写的内容主要与大家交流学习使用,如有发现任何问题敬请指正!

相关推荐
芒克芒克4 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Bella的成长园地5 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
彷徨而立5 小时前
【C/C++】什么是 运行时库?运行时库 /MT 和 /MD 的区别?
c语言·c++
qq_417129255 小时前
C++中的桥接模式变体
开发语言·c++·算法
YuTaoShao6 小时前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
No0d1es8 小时前
电子学会青少年软件编程(C语言)等级考试试卷(三级)2025年12月
c语言·c++·青少年编程·电子学会·三级
bjxiaxueliang8 小时前
一文掌握C/C++命名规范:风格、规则与实践详解
c语言·开发语言·c++
xu_yule9 小时前
网络和Linux网络-13(高级IO+多路转接)五种IO模型+select编程
linux·网络·c++·select·i/o
2301_765703149 小时前
C++与自动驾驶系统
开发语言·c++·算法
Ll13045252989 小时前
Leetcode二叉树 part1
b树·算法·leetcode