树的中序遍历

来源:互联网 发布:ncbi aspera 上传数据 编辑:程序博客网 时间:2024/06/06 04:43

中序遍历:先访问每个节点的左孩子,再访问节点本身,最后访问节点的右孩子

递归实现

public static void midOrder(BinaryTree root) {        if (root == null)            throw new IllegalArgumentException("请输入一棵树!");        if (root.getLeft() != null) {            midOrder(root.getLeft());        }        System.out.print(root.getData()+"\t");        if (root.getRight() != null) {            midOrder(root.getRight());        }    }

用栈实现

public static void inOrderUnRecur(BinaryTree root) {       if (root != null) {           Stack<BinaryTree> stack = new Stack<>();           while (!stack.isEmpty() || root != null) {               if (root != null) {                   stack.push(root);                   root = root.getLeft();               } else {                   root = stack.pop();                   System.out.print(root.getData()+"\t");                   root = root.getRight();               }           }       }        System.out.println();    }

空间复杂度都是树的深度

阅读全文
0 0