二叉树

作者: ttyttytty | 来源:发表于2021-04-08 22:17 被阅读0次
public class BinaryTreeTest {

    public static void main(String[] args) {
        TreeNode treeRootNode = BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 9, null, null, 10, null)));
        TreeNode treeRootNode2 = BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 1, null, null, 10, null)));
//        preOrderTravel(treeRootNode, "根");
//        preOrderTravelByStack(treeRootNode);
//        inorderTravel(treeRootNode, "根");
//        postOrderTravel(treeRootNode, "根");
//        postOrderTravelByStack(treeRootNode);

//        perNodeAddOne(treeRootNode);
//        System.out.println(isTwoTreeEqual(BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 1, null, null, 10, null))), BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 1, null, null, 10, null)))));

        System.out.println(isBinarySearchTree(BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 1, null, null, 10, null)))));
        System.out.println(isValidBST(BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 1, null, null, 10, null, null, 11, null, null)))));
        System.out.println(isValidBST(BinaryTreeTest.createBinaryTreePreOrder(new LinkedList<>(Arrays.asList(3, 2, 11)))));
    }

    //是否是二叉排序树/二叉搜索树(任意左节点<根&&根的右子树,任意右节点>根&&根的左子树)!!右节点需要小于当前根节点的父节点
    // 错误:(左值<根值<右值)
    public static boolean isBinarySearchTree(TreeNode treeNode) {
        if (treeNode == null) {
            return true;
        }
        if (treeNode.leftNode != null && treeNode.leftNode.val >= treeNode.val) {
            return false;
        }
        if (treeNode.rightNode != null && treeNode.val >= treeNode.rightNode.val) {
            return false;
        }
        return isBinarySearchTree(treeNode.leftNode) && isBinarySearchTree(treeNode.rightNode);
    }

    static boolean isValidBST(TreeNode root) {
        return isValidBST(root, null, null);
    }

    static boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {
        if (root == null) return true;
        System.out.println("root: " + root.val + ", min: " + (min == null ? "null" : min.val) + " , max : " + (max == null ? "null" : max.val));
        if (min != null && root.val <= min.val) return false;
        if (max != null && root.val >= max.val) return false;
        return isValidBST(root.leftNode, min, root) && isValidBST(root.rightNode, root, max);//更新最大最小值的节点,往左分支,当前根一定是下面左节点的最大;往右分支,当前根一定是下面右节点的最小
    }

    //两颗二叉树相等
    public static boolean isTwoTreeEqual(TreeNode tree1Node, TreeNode tree2Node) {
        if ((tree1Node == null) != (tree2Node == null)) {
            return false;
        }
        if (tree1Node == null) {
            return true;
        }
        return tree1Node.val == tree2Node.val && isTwoTreeEqual(tree1Node.leftNode, tree2Node.leftNode) && isTwoTreeEqual(tree1Node.rightNode, tree2Node.rightNode);
    }

    //每个节点加一
    public static void perNodeAddOne(TreeNode treeRootNode) {
        if (treeRootNode == null) {
            return;
        }
        TreeNode nodeTmp = treeRootNode;
        nodeTmp.val++;
        perNodeAddOne(nodeTmp.leftNode);
        perNodeAddOne(nodeTmp.rightNode);
    }

    //前序构建二叉树
    public static TreeNode createBinaryTreePreOrder(LinkedList<Integer> inputList) {
        if (null == inputList || inputList.size() < 1) {
            return null;
        }
        Integer data = inputList.removeFirst();
        TreeNode node = null;
        if (null != data) {
            node = new TreeNode(data);//根
            node.leftNode = createBinaryTreePreOrder(inputList);//左
            node.rightNode = createBinaryTreePreOrder(inputList);//右
        }
        return node;
    }

    //前序遍历
    public static void preOrderTravel(TreeNode treeRootNode, String index) {
        if (treeRootNode == null) {
            System.out.println("空 " + index);
            return;
        }
        //根
        System.out.println(treeRootNode.val + index);
        //左
        preOrderTravel(treeRootNode.leftNode, "左");
        //右
        preOrderTravel(treeRootNode.rightNode, "右");
    }

    //中序遍历
    public static void inorderTravel(TreeNode treeRootNode, String index) {
        if (null == treeRootNode) {
            System.out.println("空 " + index);
            return;
        }
        inorderTravel(treeRootNode.leftNode, "左");
        System.out.println(treeRootNode.val + index);
        inorderTravel(treeRootNode.rightNode, "右");
    }

    //后序遍历
    public static void postOrderTravel(TreeNode treeNode, String index) {
        if (null == treeNode) {
            System.out.println("空 " + index);
            return;
        }
        postOrderTravel(treeNode.leftNode, "左");
        postOrderTravel(treeNode.rightNode, "右");
        System.out.println(treeNode.val + index);
    }

    /**
     * 栈实现前序遍历
     *
     * @param treeRootNode
     */
    public static void preOrderTravelByStack(TreeNode treeRootNode) {
        if (treeRootNode == null) {
            return;
        }
        TreeNode rootNode = treeRootNode;
        Stack<TreeNode> stack = new Stack<>();
        while (rootNode != null || !stack.isEmpty()) {
            //循环访问左节点
            //前序:持续找左节点
            while (rootNode != null) {
                System.out.println(rootNode.val);
                stack.push(rootNode);
                rootNode = rootNode.leftNode;
                System.out.println("left:" + rootNode);
            }
            {
                System.out.println("空");
            }
            //前序:本次遍历,左节点为空,弹出栈顶的最近根节点,变访问节点为右节点
            //没有左节点,弹出栈顶节点,访问右节点
            if (!stack.isEmpty()) {
                rootNode = stack.pop();
                System.out.println(rootNode);
                rootNode = rootNode.rightNode;
                System.out.println("right:" + rootNode);
            }
        }
    }

    /**
     * 栈实现后续遍历
     * 与前序相同,仅输出位置不一致
     *
     * @param treeRootNode
     */
    public static void postOrderTravelByStack(TreeNode treeRootNode) {
        if (treeRootNode == null) {
            return;
        }
        TreeNode rootNode = treeRootNode;
        Stack<TreeNode> stack = new Stack<>();
        while (rootNode != null || !stack.isEmpty()) {
            //循环访问左节点
            while (rootNode != null) {
                System.out.println(rootNode.val);
                stack.push(rootNode);
                rootNode = rootNode.leftNode;
            }
            //没有左节点,弹出栈顶节点,访问右节点
            if (!stack.isEmpty()) {
                rootNode = stack.pop();
                System.out.println("root:" + rootNode);
                rootNode = rootNode.rightNode;
                System.out.println("right:" + rootNode);
            }
            {
                System.out.println("空");
            }
        }
    }

    //前序+标记是否出栈
    public static void postOrderByStack(TreeNode node) {
        if (node == null)
            return;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = node;
        TreeNode lastRoot = null;//标识是否已经出栈
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.leftNode;
            }
            //查询栈顶元素
            cur = stack.peek();
            //右子树为空或者右子树已经处理过,输出根
            if (cur.rightNode == null || lastRoot == cur.rightNode) {
                lastRoot = stack.pop();//出栈,标识是否已经处理过
                System.out.print(lastRoot);
                cur = null;
            } else {
                cur = cur.rightNode;
            }
        }
    }

    //队列
    public static void levelOrderTravel(TreeNode node) throws InterruptedException {
        if (node == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(node);
        while (!queue.isEmpty()) {
            TreeNode curNode = queue.poll();
            System.out.println("levelOrderTravel:" + curNode);
            if (curNode.leftNode != null) {
                queue.offer(curNode.leftNode);
            }
            if (curNode.rightNode != null) {
                queue.offer(curNode.rightNode);
            }
        }
    }

    private static class TreeNode {
        private int val;
        private TreeNode leftNode;
        private TreeNode rightNode;

        public TreeNode() {
        }

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

        @Override
        public String toString() {
            return "TreeNode{" +
                    "data=" + val +
                    '}';
        }
    }
}

相关文章

  • 数据结构与算法-二叉树02

    二叉树的定义 二叉树的特点 二叉树的五中基本形态 其他二叉树 斜二叉树 满二叉树 完全二叉树图片.png满二叉树一...

  • 二叉树

    二叉树 高度 深度真二叉树 满二叉树 完全二叉树 二叉树遍历前序 中序 后序层序遍历 翻转二叉树 递归法...

  • 二叉树 基础操作

    二叉树的使用 二叉树结构 先序创建二叉树 DFS 先序遍历二叉树 中序遍历二叉树 后序遍历二叉树 BFS 层次遍历...

  • 树与二叉树

    **树 ** 二叉树 满二叉树 完全二叉树 三种遍历方法 树与二叉树的区别 二叉查找树 平衡二叉树 红黑二叉树

  • 二叉树的宽度优先搜索(层次遍历,BFS)

    二叉树结构: 二叉树宽度优先搜索: 按照二叉树的层数依次从左到右访问二叉树的节点;例如:给定一个二叉树: 按照宽度...

  • 剑指 offer:39、平衡二叉树

    39. 平衡二叉树 题目描述 输入一棵二叉树,判断该二叉树是否是平衡二叉树。 解题思路: 平衡二叉树:Wiki:在...

  • Algorithm小白入门 -- 二叉树

    二叉树二叉树构造二叉树寻找重复子树 1. 二叉树 基本二叉树节点如下: 很多经典算法,比如回溯、动态规划、分治算法...

  • 14-树&二叉树&真二叉树&满二叉树

    一、树 二、二叉树 三、真二叉树 四、满二叉树

  • 二叉树的应用

    完美二叉树(满二叉树) 除了最下一层的节点外,每层节点都有两个子节点的二叉树为满二叉树 完全二叉树 除二叉树最后一...

  • 12.树Tree(2)

    目录:1.二叉树的基本概念2.二叉树的性质3.二叉树的创建4.二叉树的遍历 1.二叉树的基本概念 2.二叉树的性质...

网友评论

      本文标题:二叉树

      本文链接:https://www.haomeiwen.com/subject/xllpkltx.html