《程序员代码面试指南》第三章 二叉树问题

构造在第三章中使用的二叉树


/**
 * @Description:二叉树
 * @Author: lizhouwei
 * @CreateDate: 2018/4/14 9:32
 * @Modify by:
 * @ModifyDate:
 */
public class NodeUtil {
    //生成树
    public static Node generTree(int[] arr, int left, int right) {
        if (left > right) {
            return null;
        }
        int min = (left + right) / 2;
        Node head = new Node(arr[min]);
        head.left = generTree(arr, left, min - 1);
        head.right = generTree(arr, min + 1, right);
        return head;
    }

    //前序
    public static void preOrder(Node head) {
        if (head == null) {
            return;
        }
        Stack<Node> stack = new Stack<Node>();
        stack.push(head);
        while (!stack.isEmpty()) {
            head = stack.pop();
            System.out.print(head.value + " ");
            if (head.right != null) {
                stack.push(head.right);
            }
            if (head.left != null) {
                stack.push(head.left);
            }
        }
    }

    //中序遍历
    public static void inOrder(Node head) {
        if (head == null) {
            return;
        }
        Stack<Node> stack = new Stack<Node>();
        while (!stack.isEmpty() || head != null) {
            if (head != null) {
                stack.push(head);
                head = head.left;
            } else {
                head = stack.pop();
                System.out.print(head.value + " ");
                head = head.right;
            }
        }
    }

    //后序
    public static void postOrder(Node head) {
        if (head == null) {
            return;
        }
        Node cur = null;
        Stack<Node> stack = new Stack<Node>();
        stack.push(head);
        while (!stack.isEmpty()) {
            cur = stack.peek();
            if (cur.left != null && cur.left != head && cur.right != head) {
                stack.push(cur.left);
            } else if (cur.right != null && cur.right != head) {
                stack.push(cur.right);
            } else {
                head = stack.pop();
                System.out.print(head.value + " ");
            }
        }
    }
}

class Node {
    public int value;
    public Node left;
    public Node right;

    public Node() {
    }

    public Node(int value) {
        this.value = value;
    }
}
原文地址:https://www.cnblogs.com/lizhouwei/p/8830428.html