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

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

相关推荐
故事和你9110 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__10 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__11 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程12 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程12 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒12 小时前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣12 小时前
力扣热门100题之零钱兑换
算法·leetcode
leaves falling12 小时前
C++模板进阶
开发语言·c++
无敌昊哥战神13 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__13 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode