Classical algorithm - 01. Traversal of binary tree

0. Traversal of binary tree

  • The traversal of binary tree is divided into pre order traversal, middle order traversal, post order traversal and sequence traversal.
  • Among them, pre order traversal, middle order traversal and post order traversal have stack and recursion respectively, and sequence traversal has queue.
  • The recursive implementation is relatively simple, focusing on the stack implementation. The stack implementation of pre order traversal and middle order traversal is relatively similar, and the stack implementation of post order traversal is slightly different, which is the top priority.
  • Take the following binary tree as an example to briefly describe four traversals.

1. Preorder traversal

  • The preorder traversal results of binary tree are: 1, 2, M, N, 3, true, false.
  • The access order of preorder traversal is root node - left subtree - right subtree.
  • In the stack implementation, starting from the root node 1, after accessing the end point, press the node into the stack, and then access the left subtree 2 of the node, and cycle until the left subtree is null. At this time, the pointer points to the left subtree of node M at the leftmost end of the whole binary tree, which is null. Pop up a node from the stack, that is, the leftmost node M, and then point the pointer to its right subtree to enter the next cycle. When the pointer points to null and the stack is empty, the loop ends.

2. Middle order traversal

  • The middle order traversal result of binary tree is: M, 2, N, 1, true, 3, false.
  • The access order of middle order traversal is left subtree root node right subtree.
  • In the stack implementation, it is similar to the preorder traversal, except that the preorder traversal accesses the node before pushing the node into the stack, while the middle order traversal accesses the node when it pops up from the stack.

3. Post order traversal

  • The post order traversal result of binary tree is: M, N, 2, true, false, 3, 1.
  • The access order of post order traversal is left subtree right subtree root node.
  • According to the process of pre order traversal and mid order traversal, it is found that there is no opportunity for post order access to nodes, but it is found that if the access order of pre order traversal is changed to root node right subtree left subtree, and then the access order is reversed as a whole, the access order of post order traversal is obtained.
  • You can use LinkedList instead of ArrayList to access nodes. Each time you access, add elements to the head of the linked list, and then traverse in the order of root node - right subtree - left subtree to get the results of subsequent traversal.

4. Sequence traversal

  • The sequence traversal results of binary tree are: 1, 2, 3, M, N, true, false.
  • The access order of sequence traversal is from top to bottom and from left to right.
  • Sequence traversal can be easily realized by using the characteristics of queue first in first out.

5. Code

import java.util.*;

public class Test {
    public static void main(String[] args) {
        TreeNode<Object> node1 = new TreeNode<>(1);
        TreeNode<Object> node2 = new TreeNode<>(2);
        TreeNode<Object> node3 = new TreeNode<>(3);
        TreeNode<Object> node4 = new TreeNode<>("M");
        TreeNode<Object> node5 = new TreeNode<>("N");
        TreeNode<Object> node6 = new TreeNode<>(true);
        TreeNode<Object> node7 = new TreeNode<>(false);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        System.out.println("Preorder traversal(Stack implementation): " + Preorder.stack(node1));
        System.out.println("Preorder traversal(Recursive implementation): " + Preorder.recur(node1));
        System.out.println("Medium order traversal(Stack implementation): " + Inorder.stack(node1));
        System.out.println("Medium order traversal(Recursive implementation): " + Inorder.recur(node1));
        System.out.println("Postorder traversal(Stack implementation): " + Postorder.stack(node1));
        System.out.println("Postorder traversal(Recursive implementation): " + Postorder.recur(node1));
        System.out.println("level traversal (Queue implementation): " + Floor.queue(node1));
    }
}

class TreeNode<T> {
    public T val;
    public TreeNode<T> left;
    public TreeNode<T> right;

    public TreeNode(T val) {
        this.val = val;
    }
}

class Preorder {
    public static <T> List<T> stack(TreeNode<T> root) {
        List<T> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode<T>> stack = new LinkedList<>();
        TreeNode<T> cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                //TODO
                res.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            cur = cur.right;
        }
        return res;
    }

    public static <T> List<T> recur(TreeNode<T> root) {
        List<T> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        recur(root, res);
        return res;
    }

    private static <T> void recur(TreeNode<T> root, List<T> res) {
        if (root == null) {
            return;
        }
        //TODO
        res.add(root.val);
        recur(root.left, res);
        recur(root.right, res);
    }
}

class Inorder {
    public static <T> List<T> stack(TreeNode<T> root) {
        List<T> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode<T>> stack = new LinkedList<>();
        TreeNode<T> cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            //TODO
            res.add(cur.val);
            cur = cur.right;
        }
        return res;
    }

    public static <T> List<T> recur(TreeNode<T> root) {
        List<T> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        recur(root, res);
        return res;
    }

    private static <T> void recur(TreeNode<T> root, List<T> res) {
        if (root == null) {
            return;
        }
        recur(root.left, res);
        //TODO
        res.add(root.val);
        recur(root.right, res);
    }
}

class Postorder {
    public static <T> List<T> stack(TreeNode<T> root) {
        LinkedList<T> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode<T>> stack = new LinkedList<>();
        TreeNode<T> cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                //TODO
                res.addFirst(cur.val);
                stack.push(cur);
                cur = cur.right;
            }
            cur = stack.pop();
            cur = cur.left;
        }
        return res;
    }

    public static <T> List<T> recur(TreeNode<T> root) {
        List<T> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        recur(root, res);
        return res;
    }

    private static <T> void recur(TreeNode<T> root, List<T> res) {
        if (root == null) {
            return;
        }
        recur(root.left, res);
        recur(root.right, res);
        //TODO
        res.add(root.val);
    }
}

class Floor {
    public static <T> List<T> queue(TreeNode<T> root) {
        List<T> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode<T>> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode<T> cur;
        while (!queue.isEmpty()) {
            cur = queue.poll();
            if (cur != null) {
                //TODO
                res.add(cur.val);
                queue.offer(cur.left);
                queue.offer(cur.right);
            }
        }
        return res;
    }
}

Tags: Algorithm

Posted on Mon, 18 Oct 2021 19:35:17 -0400 by Loriq