数据结构 -- 二叉排序树的遍历

中序遍历

  • 中序遍历就是我们常说的左 - 根 - 右
  • 这种遍历在二叉排序树中可以顺序输出各个子节点
public void printTree(){
   if(isEmpty())
        System.out.println("Empty tree");
    else
        printTree(root);
}

public void printTree(BinaryNode<T> t){
    printTree(t.left);
    System.out.println(t.element);
    printTree(t.right);
}

后序遍历

  • 后序遍历就是我们常说的左 - 右 - 根
  • 这里一般用于计算书的高度使用。
public int height(BinaryNode<T> t){
	    if(t == null)
	         return -1;
	     else
	         return Math.max(height(t.left),height(t.right))+1;
    }
}

先序遍历

  • 后序遍历就是我们常说的==根 - 左 - 右 ==
  • 当前节点在孩子节点之前处理。
发布了134 篇原创文章 · 获赞 91 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/weixin_44588495/article/details/102791374