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 天前
算法竞赛C++常用的STL
c++·算法
weilx12344 天前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛4 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·4 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁4 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven4 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码4 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎
此生决int4 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++