解决方案 »

  1.   

    自带泛型,产品级代码,无需递归,拿走接分package base;import java.util.LinkedList;
    import java.util.Queue;class Node<T>{
    public T data;
    public Node<T> left;
    public Node<T> right;
    public Node(T data, Node<T> left, Node<T> right) {
    super();
    this.data = data;
    this.left = left;
    this.right = right;
    };

    }
    public class Tree<T> {
    public Node<T> root;
    public Tree(Node<T> root) {
    super();
    this.root = root;
    }
    //层序遍历
    @Override
    protected Node<T> clone() throws CloneNotSupportedException {
    Queue<Node<T>> que=new LinkedList<Node<T>>();
    que.offer(root);
    Queue<Node<T>> que2=new LinkedList<Node<T>>();
    Node<T> newRoot=new Node<T>(root.data, null, null);
    que2.offer(newRoot);
    Node<T> newP;
    while(!que.isEmpty()){
    Node<T> p=que.poll();
    newP=que2.poll();
    if(p.left!=null){
    newP.left=new Node<T>(p.left.data, null, null);
    que.offer(p.left);
    que2.offer(newP.left);
    }
    if(p.right!=null){
    newP.right=new Node<T>(p.right.data, null, null);
    que.offer(p.right);
    que2.offer(newP.right);
    }
    }
    return newRoot;
    }
    /**
     * 中序输出,用于测试
     */
    public static <E> void midOrder(Node<E> p){
    if(p!=null){
    midOrder(p.left);
    System.out.print(p.data+" ");
    midOrder(p.right);
    }
    }public static void main(String[] args) throws CloneNotSupportedException {
    Node<Integer> n5=new Node<Integer>(5, null, null);
    Node<Integer> n4=new Node<Integer>(4, null, null);
    Node<Integer> n2=new Node<Integer>(2, null, n5);
    Node<Integer> n3=new Node<Integer>(3, n4, null);
    Node<Integer> root1=new Node<Integer>(1, n2, n3);
    Tree<Integer> tree=new Tree<Integer>(root1);
    Node<Integer> root2=tree.clone();
    System.out.println("旧树:");
    midOrder(root1);
    System.out.println("\n新树:");
    midOrder(root2);
    }
    }
    结果:旧树:
    2 5 1 4 3 
    新树:
    2 5 1 4 3 
      

  2.   

    这个比较基础:   http://www.kaikeba.com/courses/42
    这个比较深入:   http://v.163.com/special/opencourse/algorithms.html