一个二叉树的节点有如下结构
struct node { int key; struct node *left,*right,*random; }
思路:
1. Create new nodes in cloned tree and insert each new node in original tree between the left pointer edge of corresponding node in the original tree (See the below image).
i.e. if current node is A and it’s left child is B ( A — >> B ), then new cloned node with key A wil be created (say cA) and it will be put as A — >> cA — >> B (B can be a NULL or a non-NULL left child). Right child pointer will be set correctly i.e. if for current node A, right child is C in original tree (A — >> C) then corresponding cloned nodes cA and cC will like cA —- >> cC
2. Set random pointer in cloned tree as per original tree
i.e. if node A’s random pointer points to node B, then in cloned tree, cA will point to cB (cA and cB are new node in cloned tree corresponding to node A and B in original tree)
3. Restore left pointers correctly in both original and cloned tree
下面给出step1和step3的两个函数,这两个函数的input是只有左右孩子的节点,但是可以很容易地把这两个函数扩展。#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
#include <string.h>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#define INT_MIN -100
#define INT_MAX 100
struct Node{
int key; Node* left; Node* right;
Node(int k, Node* l, Node* r): key(k), left(l), right(r){};
};
void copyLeftRight(Node* root)
// step 1
{
if(root)
{
copyLeftRight(root->left);
copyLeftRight(root->right);
Node* newRoot = new Node(root->key, NULL, NULL);
newRoot->left = root->left;
if(root->right)
newRoot->right = root->right->left;
root->left = newRoot;
}
}
void restoreTree(Node* root)
// step 3
{
if(root)
{
Node*left = root->left;
if(left)
{
root->left = left->left;
if(root->left)
left->left = root->left->left;
}
restoreTree(root->left);
restoreTree(root->right);
}
}
void printTree(Node* root)
{
if(root==NULL)
return;
cout<<root->key<<" ";
printTree(root->left);
printTree(root->right);
}
int main()
{
Node* n1 = new Node(1,NULL,NULL);
Node* n3 = new Node(3,NULL,NULL);
Node* n2 = new Node(2,n1,n3);
Node* n5 = new Node(5,NULL,NULL);
Node* n4 = new Node(4,n2,n5);
Node* n0 = new Node(0, NULL, n4);
/* Constructed binary tree is
0
\
4
/ \
2 5
/ \
1 3 */
copyLeftRight(n0);
Node* n0_copy = n0->left;
restoreTree(n0);
printTree(n0);
cout<<endl;
printTree(n0_copy);
}
完整的解法见:
http://www.geeksforgeeks.org/clone-binary-tree-random-pointers/