The front, middle and back order traversal of the binary tree and the reconstruction of the depth, leaf nodes and binary tree

Table of contents

binary tree

Binary tree creation and nested printing

create binary tree

Nested printing

Front, middle and back order traversal of binary tree

front-middle-back order traversal

level traversal

The depth of the binary tree and the number of leaf nodes

Demonstrate the results of each traversal and the number of depth and leaf nodes

Reconstruction of binary tree


binary tree

A binary tree is a data structure consisting of nodes, and each node has at most two child nodes, called left child and right child. A node can also have no child nodes, in which case the node is a leaf node.

There are many different types of binary trees, the more common ones include binary search trees, balanced binary trees, red-black trees, etc. The characteristic of a binary search tree is that for each node, the values ​​of all nodes in its left subtree are smaller than its value, and the values ​​of all nodes in its right subtree are greater than its value. This makes binary search trees fast for finding, inserting, and deleting nodes, with a time complexity of O(log n).

Binary tree creation and nested printing

First use a class to encapsulate the nodes of the binary tree

public class TreeNode {
    int data;//数据
    TreeNode left;//左子节点
    TreeNode right;//右子节点

    public TreeNode(){};
    //构造函数
    public TreeNode(int data, TreeNode left, TreeNode right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
}

create binary tree

public class BinaryTree {
    Scanner scanner = new Scanner(System.in);
    TreeNode root = null;//二叉树的根,默认为空
     public TreeNode createBinaryTree() {//创建二叉树
        TreeNode t;//当前树的根
        int x = scanner.nextInt();//输入当前节点的值,如果为0则表示空节点
        if (x == 0) {
            t = null;
        } else {
            t = new TreeNode();
            t.data = x;//data为往前节点的数值
            t.left = createBinaryTree();
            t.right = createBinaryTree();
        }
        return t;
    }
}

Nested printing

public void printTree(TreeNode t) {//嵌套打印
        if (t != null) {
            System.out.print(t.data);//输出根节点
            if (t.left != null || t.right != null) {
                //只要左子节点和右子节点有一个不为空就输出
                System.out.print("(");
                printTree(t.left);//递归调用左子节点
                if (t.right != null) {
                    System.out.print(",");
                }
                printTree(t.right);
                System.out.print(")");
            }
        }
    }

Front, middle and back order traversal of binary tree

 

The traversal of a binary tree refers to visiting each node in the tree in a certain order. The three traversal methods of binary tree are pre-order traversal, in-order traversal and post-order traversal. The order of pre-order traversal is root node-left subtree-right subtree , the order of in-order traversal is left subtree-root node-right subtree , and the order of post-order traversal is left subtree-right subtree-root node .

front-middle-back order traversal

public void preOrder(TreeNode root) {//前序遍历 根节点-左子树-右子树
        if (root != null) {
            System.out.print(root.data + " ");
            preOrder(root.left);
            preOrder(root.right);
        }
    }

    public void midOrder(TreeNode root) {//中序遍历 左子树-根节点-右子树
        if (root != null) {
            midOrder(root.left);
            System.out.print(root.data + " ");
            midOrder(root.right);
        }
    }

    public void postOrder(TreeNode root) {//后序遍历 左子树-右子树-根节点
        if (root != null) {
            postOrder(root.left);
            postOrder(root.right);
            System.out.print(root.data + " ");
        }
    }

level traversal

public void leverOrder(TreeNode root) {//层次遍历
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if (root == null) return;
        queue.offer(root);//根入列
        while (!queue.isEmpty()) {
            TreeNode head = queue.poll();//弹出列头
            System.out.print(head.data + " ");
            if (head.left != null) {
                queue.offer(head.left);
            }
            if (head.right != null) {
                queue.offer(head.right);
            }
        }
    }

The depth of the binary tree and the number of leaf nodes

 public int treeDepth(TreeNode root) {//求二叉树的深度
        if (root == null) return 0;
        return Math.max(treeDepth(root.left), treeDepth(root.right)) + 1;
    }

    public int treeLeaf(TreeNode root) {//求二叉树的叶子数量
        if (root == null) return 0;
        else if (root.left == null && root.right == null) return 1;
        else return treeLeaf(root.left) + treeLeaf(root.right);
    }

Demonstrate the results of each traversal and the number of depth and leaf nodes

public class AppStart {
    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.root = binaryTree.createBinaryTree();
        binaryTree.printTree(binaryTree.root);//嵌套打印
        System.out.println();//换行
        binaryTree.preOrder(binaryTree.root);//前序遍历
        System.out.println();
        binaryTree.midOrder(binaryTree.root);//中序遍历
        System.out.println();
        binaryTree.postOrder(binaryTree.root);//后序遍历
        System.out.println();
        binaryTree.leverOrder(binaryTree.root);//层次遍历
        System.out.println();
        System.out.println(binaryTree.treeDepth(binaryTree.root));//深度
        System.out.println(binaryTree.treeLeaf(binaryTree.root));//叶子个数
    }
}

The input data is 1 2 4 0 0 5 0 0 3 6 0 0 7 0 0, because 4 5 6 7 is a leaf and has no cotyledon

 

Reconstruction of binary tree

 The reconstruction of the binary tree refers to the process of rebuilding the binary tree according to the known pre-order traversal and in-order traversal sequences of the binary tree. The specific process is as follows:

(1) According to the preorder traversal sequence, the first element is the root node, which is inserted into the binary tree.

(2) According to the in-order traversal sequence, find the position of the root node in it, and divide the in-order traversal sequence into left subtree and right subtree sequences.

(3) For the preorder traversal sequence, the next element of the left subtree sequence is the root node of the left subtree, and the next element of the right subtree sequence is the root node of the right subtree. Insert them into the binary tree.

(4) Recursively process the left subtree and the right subtree, repeat steps 2 and 3 until the sequence is empty or only one element remains.

import java.util.Scanner;

public class rebuiltBinaryTree {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String pre,mid;//定义前序和中序变量
        while (scanner.hasNext()) {
            pre = scanner.next();
            mid = scanner.next();
            System.out.println(f(pre,mid));
        }
    }

    public static String f(String pre, String mid) {
        if (pre.length() == 0) return "";
        else if (pre.length() == 1) return pre;
        else {
            int pos = mid.indexOf(pre.charAt(0));//根据前序的根去中序里分左右
            /*
            public int indexOf(int ch)
            返回指定字符在此字符串中第一次出现处的索引。
            如果在此 String 对象表示的字符序列中出现值为 ch 的字符,则返回第一次出现该字符的索引
             */
            String left = f(pre.substring(1, pos + 1), mid.substring(0, pos));
            /*
            public String substring(int beginIndex,int endIndex)
            返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,
            直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex
             */
            String right = f(pre.substring(pos + 1), mid.substring(pos + 1));
            /*
            public String substring(int beginIndex)
            返回一个新的字符串,它是此字符串的一个子字符串。
            该子字符串从指定索引处的字符开始,直到此字符串末尾。
             */
            return left + right + pre.charAt(0);//前序的第一个字符是根
        }
    }
}

 

 

Guess you like

Origin blog.csdn.net/weixin_71646897/article/details/129910738