克隆一个有随机指针的二叉树 Clone a Binary Tree with Random Pointers

一个二叉树的节点有如下结构

struct node {  
    int key; 
    struct node *left,*right,*random;
} 
指针random随机地指向树中的任意一个节点,也可以指向NULL。写出函数,克隆这棵树。

思路:

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

Binary_Tree(1)

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值