Java binary tree basic concepts (recursion & iteration)

content

1. Tree structure

1.1 Concept

1.2 Concept (important)

2. Binary tree (emphasis)

2.1 Concept

2.2 The basic form of binary tree

2.3 Two special binary trees

2.4 Properties of Binary Trees

a. Full binary tree

b. Complete binary tree

2.5 Storage of binary tree

2.6 Basic operations of binary tree

2.6.1 Binary tree traversal (recursion)

2.6.2 Traversal (iteration) of binary tree

2.6.3 Basic operations of binary tree

2.7 Level order traversal of binary tree

3. Binary tree complete code


1. Tree structure

1.1 Concept

A tree is a nonlinear data structure, which consists of n ( n>=0 ) finite nodes to form a set with hierarchical relationship. It is called a tree because it looks like an upside-down tree, that is, it has the roots up and the leaves down .

1.2 Concept (important)

a. The degree of the node: the number of subtrees of the node; as shown in the figure above: the degree of A is 6, and the degree of J is 2

b. The degree of the tree: in the tree, the degree of the largest node is the degree of the number; as shown above: the degree of the tree is 6

c. Leaf nodes (terminal nodes) : nodes with degree 0 (nodes without subtrees)

d. Parent node/parent node: as shown above: D is the parent node of H

   Child node/child node : As shown above: H is the child node of D

e. Root node: a node without parents; as shown above: A

f. The level of nodes : starting from the definition of the root, the root is the first layer , the child nodes of the root are the second layer, and so on;

g. The height or depth of the tree: the maximum level of nodes in the tree; as shown above: the height of the tree is 4

2. Binary tree (emphasis)

2.1 Concept

Each node has at most two subtrees, degree <= 2.

2.2 The basic form of binary tree

2.3 Two special binary trees

a. Full binary tree: non-cotyledon degree is 2

b. Complete binary tree: The full binary tree is missing the "lower right corner"

2.4 Properties of Binary Trees

a. Full binary tree:

1. If the height is K, there are 2^k-1 nodes

2. If the level is K, then the level has 2^(k-1) nodes

3. Number of Edges = Number of Nodes - 1

4. If the degree is 0, there are n0, and if the degree is 2, there are n2, then n0 = n2 + 1

b. Complete binary tree:

1. If there is a right child, there must be a left child

2. There can only be one node with degree 1

2.5  Storage of binary tree

The storage structure of binary tree is divided into: sequential storage and linked storage similar to linked list .

Sequential storage: only complete binary trees can be stored

Chained Storage: Ordinary Binary Tree

This show chain storage

The chain storage of the binary tree is referenced through one node, and the common representations include binary and ternary representations .
Take this picture as an example, as follows:
// 孩子表示法
private static class TreeNode{
    char val;
    TreeNode left;
    TreeNode right;

    public TreeNode(char val) {
        this.val = val;
    }
}
initialization:
    public static TreeNode build(){
        TreeNode nodeA=new TreeNode('A');
        TreeNode nodeB=new TreeNode('B');
        TreeNode nodeC=new TreeNode('C');
        TreeNode nodeD=new TreeNode('D');
        TreeNode nodeE=new TreeNode('E');
        TreeNode nodeF=new TreeNode('F');
        TreeNode nodeG=new TreeNode('G');
        TreeNode nodeH=new TreeNode('H');
        nodeA.left=nodeB;
        nodeA.right=nodeC;
        nodeB.left=nodeD;
        nodeB.right=nodeE;
        nodeE.right=nodeH;
        nodeC.left=nodeF;
        nodeC.right=nodeG;
        return nodeA;
    }

2.6 Basic operations of binary trees

2.6.1 Binary tree traversal (recursion)

1. NLR : Preorder traversal (Preorder Traversal also known as preorder traversal ) - visit the root node ---> the left subtree of the root ---> the right subtree of the root.
    //先序遍历 : 根左右
    public static void preOrder(TreeNode root){
        if(root==null){
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }
2. LNR : Inorder Traversal - left subtree of the root --- > root node ---> right subtree of the root.
    //中序遍历
    public static void inOrder(TreeNode root){
        if(root==null){
            return;
        }
        preOrder(root.left);
        System.out.print(root.val+" ");
        preOrder(root.right);
    }
3. LRN : Postorder Traversal - left subtree of the root ---> right subtree of the root ---> root node.
    //后序遍历
    public static void postOrder(TreeNode root){
        if(root==null){
            return;
        }
        preOrder(root.left);
        preOrder(root.right);
        System.out.print(root.val+" ");
    }

2.6.2  Traversal (iteration) of binary tree

1. Preorder traversal

    //方法2(迭代)
    //先序遍历 (迭代)
    public static void preOrderNonRecursion(TreeNode root){
        if(root==null){
            return ;
        }
        Deque<TreeNode> stack=new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode cur=stack.pop();
            System.out.print(cur.val+" ");
            if(cur.right!=null){
                stack.push(cur.right);
            }
            if(cur.left!=null){
                stack.push(cur.left);
            }
        }
    }

2. Inorder traversal

    //方法2(迭代)
    //中序遍历 (迭代)
    public static void inorderTraversalNonRecursion(TreeNode root) {
        if(root==null){
            return ;
        }

        Deque<TreeNode> stack=new LinkedList<>();
        // 当前走到的节点
        TreeNode cur=root;
        while (!stack.isEmpty() || cur!=null){
            // 不管三七二十一,先一路向左走到根儿~
            while (cur!=null){
                stack.push(cur);
                cur=cur.left;
            }
            // 此时cur为空,说明走到了null,此时栈顶就存放了左树为空的节点
            cur=stack.pop();
            System.out.print(cur.val+" ");
            // 继续访问右子树
            cur=cur.right;
        }
    }

3. Post-order traversal

    //方法2(迭代)
    //后序遍历 (迭代)
    public static void postOrderNonRecursion(TreeNode root){
        if(root==null){
            return;
        }
        Deque<TreeNode> stack=new LinkedList<>();
        TreeNode cur=root;
        TreeNode prev=null;

        while (!stack.isEmpty() || cur!=null){
            while (cur!=null){
                stack.push(cur);
                cur=cur.left;
            }

            cur=stack.pop();
            if(cur.right==null || prev==cur.right){
                System.out.print(cur.val+" ");
                prev=cur;
                cur=null;
            }else {
                stack.push(cur);
                cur=cur.right;
            }
        }
    }

2.6.3  Basic operations of binary trees

1. Find the number of nodes (recursion & iteration)
    //方法1(递归)
    //传入一颗二叉树的根节点,就能统计出当前二叉树中一共有多少个节点,返回节点数
    //此时的访问就不再是输出节点值,而是计数器 + 1操作
    public static int getNodes(TreeNode root){
        if(root==null){
            return 0;
        }
        return 1+getNodes(root.left)+getNodes(root.right);
    }

    //方法2(迭代)
    //使用层序遍历来统计当前树中的节点个数
    public static int getNodesNoRecursion(TreeNode root){
        if(root==null){
            return 0;
        }
        int size=0;
        Deque<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            size++;
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
        return size;
    }
2. Find the number of leaf nodes (recursion & iteration)
    //方法1(递归)
    //传入一颗二叉树的根节点,就能统计出当前二叉树的叶子结点个数
    public static int getLeafNodes(TreeNode root){
        if(root==null){
            return 0;
        }
        if(root.left==null && root.right==null){
            return 1;
        }
        return getLeafNodes(root.left)+getLeafNodes(root.right);
    }

    //方法2(迭代)
    //使用层序遍历来统计叶子结点的个数
    public static int getLeafNodesNoRecursion(TreeNode root){
        if(root==null){
            return 0;
        }
        int size=0;
        Deque<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur=queue.poll();
            if(cur.left==null && cur.right==null){
                size++;
            }
            if(cur.left!=null){
                queue.offer(cur.left);
            }
            if(cur.right!=null){
                queue.offer(cur.right);
            }
        }
        return size;
    }

3. Find the number of nodes in the kth layer
    //求出以root为根节点的二叉树第k层的节点个数
    public static int getKLevelNodes(TreeNode root,int k){
        if(root==null || k<=0){
            return 0;
        }
        if(k==1){
            return 1;
        }
        return getKLevelNodes(root.left,k-1)+getKLevelNodes(root.right,k-1);
    }

4. Find the height of the tree
    //传入一个以root为根节点的二叉树,就能求出该树的高度
    public static int height(TreeNode root){
        if(root==null){
            return 0;
        }
        return 1+ Math.max(height(root.left),height(root.right));
    }

5. Determine whether there is a node with value in the binary tree number
    //判断当前以root为根节点的二叉树中是否包含指定元素val,
    //若存在返回true,不存在返回false
    public static boolean contains(TreeNode root,char value){
        if(root==null){
            return false;
        }
        if(root.val==value){
            return true;
        }
        return contains(root.left,value) || contains(root.right,value);
    }

2.7  Level order traversal of binary tree

    //层序遍历
    public static void levelOrder(TreeNode root) {
        if(root==null){
            return ;
        }

        // 借助队列来实现遍历过程
        Deque<TreeNode> queue =new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size=queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur=queue.poll();
                System.out.print(cur.val+" ");
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
        }
    }

3. Binary tree complete code

See the following section for the complete code of the binary tree: 《Java binary tree complete code (recursion & iteration)

Guess you like

Origin blog.csdn.net/m0_62218217/article/details/123067319