遍历二叉树

来源:互联网 发布:营销推广软件 编辑:程序博客网 时间:2024/06/10 00:32

递归遍历:

public static<T> String scanTree(TNode<T> t){String result="";int n=0;if(t!=null){result+=scanTree(t.left);result+=t.nodeValue+" ";result+=scanTree(t.right);}return result;}


迭代按层遍历:

public static<T> String levelOrderDisplay(TNode<T> t){LinkedQueue<TNode<T>> p=new LinkedQueue<TNode<T>>();TNode<T> q;String s="";p.push(t);while(!p.isEmpty()){q=p.pop();s+=q.nodeValue+" ";if(q.left!=null){p.push(q.left);}if(q.right!=null){p.push(q.right);}}return s;}


 

原创粉丝点击