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

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

相关推荐
不想写代码的星星1 小时前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星1 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
端平入洛9 天前
auto有时不auto
c++
琢磨先生David10 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈202110 天前
信号量和信号
linux·c++