首页 > 其他 > 详细

树的遍历

时间:2019-08-31 20:51:15      阅读:74      评论:0      收藏:0      [点我收藏+]
  • 前序遍历:中左右
  • 中序编列:左中右
  • 后续编列:左右中
//前序遍历
public static void preOrder(Node node) {
    if (node == null) {
        return;
    }
    System.out.print(node.value);
    preOrder(node.left);
    preOrder(node.right);
}

//中序遍历
public static void inOrder(Node node) {
    if (node == null) {
        return;
    }
    inOrder(node.left);
    System.out.print(node.value);
    inOrder(node.right);
}

//后序遍历
public static void postOrder(Node node) {
    if (node == null) {
        return;
    }
    postOrder(node.left);
    postOrder(node.right);
    System.out.print(node.value);

}

/**
 * 非递归实现
 */
//前序遍历
public static void preOrder02(Node node) {
    Stack<Node> stack = new Stack<>();
    while (node != null || !stack.isEmpty()) {
        while (node != null) {
            System.out.print(node.value);
            stack.push(node);
            node = node.left;
        }
        node = stack.pop().right;

    }
}

//中序遍历
public static void inOrder02(Node node) {
    Stack<Node> stack = new Stack<>();
    while (node != null || !stack.isEmpty()) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
        node = stack.pop();
        System.out.print(node.value);
        node = node.right;
    }
}

//后序遍历
public static void postOrder2(Node node) {
    Stack<Node> stack = new Stack<Node>();
    Stack<Integer> tag = new Stack<Integer>();
    while (node != null || !stack.isEmpty()) {
        if (node != null) {
            stack.push(node);
            tag.push(1);  //第一次访问
            node = node.left;
        } else {
            if (tag.peek() == 2) {
                System.out.print(stack.pop().value);
                tag.pop();
            } else {
                tag.pop();
                tag.push(2); //第二次访问
                node = stack.peek().right;
            }
        }

    }
}

测试用例

//测试用例
public static void test(Node node) {
    System.out.print("递归_前序排序:");
    preOrder(node);
    System.out.println();
    System.out.print("前序排序:");
    preOrder02(node);
    System.out.println();
    System.out.print("递归_中序遍历:");
    inOrder(node);
    System.out.println();
    System.out.print("中序遍历:");
    inOrder02(node);
    System.out.println();
    System.out.print("递归_后序排序:");
    postOrder(node);
    System.out.println();
    System.out.print("后序排序:");
    postOrder2(node);
    System.out.println();
}
public static void main(String[] args) {
    BST<Integer, Integer> bst = new BST<>();
    bst.put(3, 3);
    bst.put(2, 2);
    bst.put(4, 4);
    TreeOrder.test(bst.root);
}

输出

递归_前序排序:324
前序排序:324
递归_中序遍历:234
中序遍历:234
递归_后序排序:243
后序排序:243

树的遍历

原文:https://www.cnblogs.com/aiguozou/p/11440207.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!