Summary of binary tree traversal methods

1. Binary tree preorder traversal recursive and iterative methods.

Around the root, traverse to push the root into the stack, and then push the right subtree and the left subtree. Since the root is in front (left and right of the root), every time the child traverses the root, it will come out after pressing it in, and the properties of the root can be ignored. Due to the characteristics of the stack. The order in which the left and right subtrees are pressed is reversed. Refer to the   picture   .

Recite: push(root) while the stack is not empty, pop up, press right and left

    public static void preOrderRecur(TreeNode head) {
        if (head == null) {
            return;
        }
        System.out.print(head.value + " ");//res.add(head.val)
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }
------------------------------------------------------------

  public void preorderTraversal(TreeNode p) {
        if (p == null) return;
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(p);
        while (!stack.isEmpty()) {
            TreeNode tmp = stack.poll();
            Syst

Guess you like

Origin blog.csdn.net/yu1336199790/article/details/111395857