Thread: How to duplicate a tree?

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    163

    How to duplicate a tree?

    Hi!

    How do a duplicate a tree in the shortest way? My tree is implemented using linked list.

    Each node contains a value, a pointer to its next sibling, a pointer to its first child.

    For an example, the tree looks like this. Do not worry about how the tree is ordered in this way, I just like to know how do I duplicate the whole thing out? My current idea is use recursive function to tranverse the nodes to duplicate each node.
    Code:
    Root
    |
    (1)--------(3)---(5)
    |               |       |
    (2)--(6)    (5)   (2)--(3)--(1)
    Thanks for your help!
    Last edited by Salem; 01-15-2005 at 04:39 AM. Reason: tagged for presentation

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well you just use your normal traversal function to visit each node. You create a copy and call your tree insert function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    163
    Yea, thanks salem! It's simpler than I thought, just a recursive function is all it takes

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary Tree Search
    By C++Newbie in forum C++ Programming
    Replies: 7
    Last Post: 04-05-2011, 01:17 AM
  2. Interpreter.c
    By moussa in forum C Programming
    Replies: 4
    Last Post: 05-28-2008, 05:59 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. BST/Red and Black Tree
    By ghettoman in forum C++ Programming
    Replies: 0
    Last Post: 10-24-2001, 10:45 PM