当前位置: 代码迷 >> J2SE >> 一个关于二叉树的简单有关问题,初学者啊
  详细解决方案

一个关于二叉树的简单有关问题,初学者啊

热度:135   发布时间:2016-04-23 20:23:48.0
一个关于二叉树的简单问题,菜鸟求救啊啊
求一个二叉树覆盖clone的方法!!!
还想问一下有没有关于数据结构的视频教程,本人菜鸟自学感觉有点压力哇
------解决方案--------------------
自带泛型,产品级代码,无需递归,拿走接分

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 

------解决方案--------------------
这个比较基础:   http://www.kaikeba.com/courses/42
这个比较深入:   http://v.163.com/special/opencourse/algorithms.html
  相关解决方案