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
    }
};

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

相关推荐
choumin4 小时前
创建型模式——工厂方法模式
c++·设计模式·工厂方法模式·创建型模式
云小逸4 小时前
【SVN 详细使用指南:从入门到团队协作】
c++·svn
ziguo11229 小时前
深入浅出 C/C++ 数据类型:从入门到踩坑
linux·c语言·c++·windows·visual studio
白色冰激凌10 小时前
[SECS/GEM研究] (三)SECS-I 串口上消息怎么分块和重传
c++·secs/gem
光头闪亮亮10 小时前
Fyne ( go跨平台GUI )项目实战-项目开发必备基础知识(中)
android·c++·go
光头闪亮亮10 小时前
Fyne ( go跨平台GUI )项目实战-项目开发必备基础知识(下)
android·c++·go
keep intensify10 小时前
最长有效括号
算法·leetcode·动态规划
CoderYanger10 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
_wyt00111 小时前
洛谷 P7912 [CSP-J 2021] 小熊的果篮 题解
c++·队列
choumin12 小时前
创建型模式——原型模式
c++·设计模式·原型模式·创建型模式