题目地址:
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
给定两棵一模一样的二叉树,再给定第一棵树中的某个节点 x x x,求第二棵树中对应的节点。
可以做DFS,同时对两棵树搜索,第一棵树中搜索到 x x x的时候,搜到的第二棵树中的节点即为所求。代码如下:
class Solution {
public:
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned,
TreeNode* target) {
return dfs(original, cloned, target);
}
TreeNode* dfs(TreeNode* t1, TreeNode* t2, TreeNode* p) {
if (!t1) return nullptr;
if (t1 == p) return t2;
auto l = dfs(t1->left, t2->left, p);
if (l) return l;
return dfs(t1->right, t2->right, p);
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h), n n n为树节点个数, h h h为树高。