java实现二叉树遍历

 

public class BTNode<E> {
    private E data; //存储在结点的数据
    private BTNode<E> left; //左孩子
    private BTNode<E> right; //右孩子

// 属性的set,get方法,此处省略,通过自动补充补充上即可。
public BTNode(E initialData, BTNode<E> initialLeft, BTNode<E> initialRight ){ data = initialData; left = initialLeft; right = initialRight; } public void print(int deep){ for(int i = 1; i <= deep; i++){ System.out.print("-"); } System.out.print( data + "\n"); if(left != null) left.print(deep + 1); if(right != null) right.print(deep + 1); } public static void main(String[] args) { BTNode<String> a = new BTNode<String>("A", null, null); BTNode<String> b = new BTNode<String>("B", null, null); BTNode<String> c = new BTNode<String>("C", null, null); BTNode<String> d = new BTNode<String>("D", null, null); BTNode<String> e = new BTNode<String>("E", null, null); BTNode<String> f = new BTNode<String>("F", null, null); a.setLeft(b); a.setRight(c); b.setLeft(d); b.setRight(e); c.setLeft(f); a.print(0); } }

 此为二叉树遍历的一种:深度优先遍历的左序遍历,根->左->右,先遍历root根节点,然后遍历完左边的节点以后再遍历右边的节点。

posted @ 2019-05-10 12:07  super超人  阅读(369)  评论(0编辑  收藏  举报