1. Title
Gives you two binary trees, the original tree original and cloned tree cloned, and a target node target located in the original tree original.
Among them, the cloned tree cloned is a copy of the original tree.
Please find the node that is the same as the target in the tree cloned, and return a reference to the node (in C / C ++ and other languages with pointers, return the node pointer, other languages return the node itself).
注意:
你 不能 对两棵二叉树,以及 target 节点进行更改。
只能 返回对克隆树 cloned 中已有的节点的引用。
进阶:如果树中允许出现值相同的节点,你将如何解答?
Source: LeetCode
link: https://leetcode-cn.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
copyright Collar network all. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
2. Problem solving
- Binary tree traversal in cyclic mode, the two trees can be synchronized
class Solution {
public:
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
stack<TreeNode*> stk1, stk2;
TreeNode *tp1, *tp2;
while(original || !stk1.empty())
{
while(original)
{
stk1.push(original);
original = original->left;
}
while(cloned)
{
stk2.push(cloned);
cloned = cloned->left;
}
tp1 = stk1.top();
tp2 = stk2.top();
stk1.pop();
stk2.pop();
if(tp1 == target)
return tp2;
original = tp1->right;
cloned = tp2->right;
}
return NULL;
}
};
872 ms 164.6 MB