Java data structure | Basic operation of binary tree

Table of contents

1. Storage method of binary tree

Second, the traversal of the binary tree

preorder traversal

Inorder traversal

post order traversal 

sequence traversal

 3. Other operations of binary tree

Get the number of nodes in the tree

Get the number of leaf nodes in the tree

Get the number of kth layer nodes

Get the depth of the binary tree


1. Storage method of binary tree

Binary trees can be stored in chains or sequentially.

Then the linked storage method uses pointers, and the sequential storage method uses arrays.

As the name implies, the sequentially stored elements are continuously distributed in the memory, while the linked storage uses pointers to connect nodes scattered at various addresses in series.

Chained storage is shown in the figure:

Chained storage is a method that everyone is familiar with, so let's take a look at how to store sequentially?

In fact, arrays are used to store binary trees, and the sequential storage method is shown in the figure:

How to use array to store binary tree traversal?

If the array subscript of the parent node is i, then its left child is i * 2 + 1, and its right child is i * 2 + 2.

But the binary tree represented by the chain is more conducive to our understanding, so generally we use the chain to store the binary tree.

So everyone should understand that a binary tree can still be represented by an array.

Second, the traversal of the binary tree

If an agreement is made according to a certain rule, everyone's traversal results for the same tree must be the same. If N represents the root node, L represents the left subtree of the root node, and R represents the right subtree of the root node, then according to the order of traversing the root nodes, there are the following traversal methods:

NLR: Preorder traversal (Preorder Traversal is also known as preorder traversal) - visit the root node ---> the left subtree of the root ---> the right subtree of the root. LNR: Inorder Traversal (Inorder Traversal) - the left subtree of the root ---> root node ---> the right subtree of the root. LRN: postorder traversal (Postorder Traversal) - left subtree of the root ---> right subtree of the root ---> root node

Layer order traversal: Starting from the root node of the binary tree, first visit the nodes of the first layer, then visit the nodes of the second layer from left to right, from top to bottom, and so on

Take the above tree as an example to briefly introduce the traversal implementation of the binary tree:

  • preorder traversal

Root node - left subtree - right subtree

The result of preorder traversal is: A B D E H C F G

//前序遍历
   public void preOrder(TreeNode root){
        if(root == null){
            return;
        }
        System.out.println(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
   }
  • Inorder traversal

Left subtree - root node - right subtree

The result of inorder traversal is: DBE HAFCG 

// 中序遍历
    public void inOrder(TreeNode root){
        if(root == null){
            return;
        }
        inOrder(root.left);
        System.out.println(root.val+" ");
        inOrder(root.right);
    }
  • post order traversal 

Left subtree - right subtree - root node

 // 后序遍历
    public void postOrde(TreeNode root){
        if(root == null){
            return;
        }
        postOrde(root.left);
        postOrde(root.right);
        System.out.println(root.val+" ");
    }
  • sequence traversal

Starting from the root node from left to right, and so on

Sequence traversal results: A B C D E F G H

The characteristics of binary tree post-order traversal: the last node must be the root node.

Pre-order traversal of a binary tree is specific: the first node must be the root node.

  • Use List to store node elements for preorder traversal

  public List<Character> preOrder2(TreeNode root){
        List<Character> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        ret.add(root.val);
        List<Character> leftTree = preOrder2(root.left);
        ret.addAll(leftTree);
        List<Character> rightTree  = preOrder2(root.right);
        ret.addAll(rightTree);
        return ret;
    }

 3. Other operations of binary tree​​​​​​

  • Get the number of nodes in the tree

To obtain the number of nodes in the tree, we can use the method of traversal, or we can use the idea of ​​sub-problems, and use the recursive method, that is, left subtree + right subtree + root node (+1) to achieve

size(root.left) +size(root.right)+1; 
   /**
     *  遍历方法
     */
    public static int nodeSize = 0;
    public int size(TreeNode root){
        if(root == null){
            return 0;
        }
        nodeSize++;
        size(root.left);
        size(root.left);
        return nodeSize;
    }
    /**
     * 子树相加再加上根节点
     * @param root
     * @return
     */
    public int size2(TreeNode root){
        if(root == null){
            return 0;
        }
        int tmp = size(root.left) +size(root.right)+1;
        return tmp;
    }
  • Get the number of leaf nodes in the tree

Get the number of leaf nodes in the tree, that is, when both the left subtree and the right subtree are empty, root.left==null&&root.right==null, the leaf nodes on the left subtree + all leaf nodes on the right subtree or Use the temporary variable leafSize++;

 /**
     * 获取叶子节点的个数
     * @param root
     * @return
     */
  //子问题思路
    public int getLeafNodeCount(TreeNode root){
        if(root == null){
            return  0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        int tmp = getLeafNodeCount(root.left)+getLeafNodeCount(root.right);
        return tmp;
    }
     //遍历方法
    public static int leafSize = 0;
    public  int getLeafNodeCount2(TreeNode root){
        if(root == null){
            return 0;
        }
        if(root.left == null&&root.right == null){
            leafSize++;
        }
        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
        return leafSize;
    }
  • Get the number of kth layer nodes

Finding the number of nodes in the kth layer can be transformed into the k-1 layer of the left tree + the k-1 layer of the right tree, that is

When K=3, convert to the number of nodes in the second layer of the left tree and the second layer of the right tree, and finally convert to when k = 1, return the node 2 of the second layer from the left and the second layer from the right The number of nodes in the third layer is 4 by adding the nodes 2

 public int getKLevelNodeCount(TreeNode root,int k){
        if(root == null|| k <= 0){
            return 0;
        }
        if(k==1){
            return 1;
        }
     int tmp = getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
      return tmp;
    }
  • Get the depth of the binary tree

public int getHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        //左右子树的最大c
        return leftHeight > rightHeight ? leftHeight+1 : rightHeight +1;
   }

 

ced485cbb11e458d81a746890b32cf3f.gif

Guess you like

Origin blog.csdn.net/m0_56361048/article/details/127303470