Find the height of the binary tree 【Java】

Overview

  Traversing a binary tree has already been mentioned in the previous article, so how to find the height of a binary tree? This lecture will talk about this issue.

Ideas

  In fact, this idea is difficult to make clear. The general meaning is to increase the height by 1 every time a layer is traversed. Then the question arises, how can I judge that this layer of traversal is over? This can be done by recording the number of each layer, and then after traversing each layer of this layer, it means that this layer has been traversed, then the question is again, how to record the number of each layer? This is a trick, the idea is this, use two traversals at the same time, when the first traversal traverses the next layer, the second traversal traverses the previous layer, when the previous layer is traversed, the next layer It will be traversed, and then in this process, you can increase the height by 1 through some flags.

  It may be more confusing to read the above ideas. Let's look at the code directly below.

The basic code is the composition of the binary tree and the code of each node.

Binary tree:

package com.example.demo.tree;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.omg.PortableInterceptor.INACTIVE;

import java.util.Comparator;

/**
 * @author steve
 * @date 2020/4/16 10:03 上午
 */
public class BinaryTree<E> {

    private int size;
    public Node<E> root;
    private Comparator<E> comparator;

    public BinaryTree(Comparator<E> comparator){
        this.comparator = comparator;
    }

    public BinaryTree(){
        this(null);
    }

    public void add(E element){
        if (root == null){
            Node node = new Node(element);
            root = node;
        }else {
            Node<E> parent = root;
            Node<E> node = root;
            int com = 0;
            while (node != null){
                parent = node;
                if (comparator == null){
                    com = ((Comparable)node.element).compareTo(element);
                }else {
                    System.out.println("-------------");
                    com = comparator.compare(node.element,element);
                }
                if (com > 0){
                    node = node.left;
                }else if (com < 0){
                    node = node.right;
                }else {
                    node.element = element;
                    return;
                }
            }
            Node<E> newNode = new Node(element);
            if (com > 0){
                parent.left = newNode;
                newNode.parent = parent.left;
            }else{
                parent.right = newNode;
                newNode.parent = parent.right;
            }
        }
        size ++;
    }
    public boolean isEmpty(){
        return size == 0;
    }
    public int size(){
        return size;
    }

    public String toString() {
        String d = root == null ? null : root.element + "";
        if (root == null){
            return "root:"+d;
        }else {
            String b = root.left == null ? null: root.left.element + "" ; 
            String c = root.right == null ? null : root.right.element + "" ;
             return "root:" + d + ", left:" + b + ", right : "+ c; 
        } 

    } 


    public  static  void main (String [] args) {
         // This method is an anonymous inner class, by passing an interface as a parameter to a class, and then this interface is implemented by an anonymous inner class Incoming implementation. 
        BinaryTree <Integer> binaryTree = new BinaryTree <> ( new Comparator <Integer> () { 
            @Override 
            public  int compare (Integer o1,
                 o1 - o2;
            }
        });

        BinaryTree<Integer> binaryTree1 = new BinaryTree<>();
        binaryTree1.add(1);
        binaryTree1.add(2);
        binaryTree1.add(0);
        System.out.println(binaryTree1.size());
        System.out.println(binaryTree.toString());
    }
}
View Code

node:

package com.example.demo.tree;

/**
 * @author steve
 * @date 2020/4/18 3:16 下午
 */
public class Node<E> {
    public Node<E> left;
    public Node<E> right;
    public Node<E> parent;
    public E element;
    public Node(E element){
        this.element = element;
    }
}
View Code

Determine the height of a binary tree

package com.example.demo.tree; 

import java.util.ArrayList;
 import java.util.List; 

/ ** 
 * @author steve 
 * @date 2020/4/20 6:36 pm 
 * @description Find the height of the binary tree , Through recursion and iteration 
 * / 
public  class BinaryTreeHeight { 

    / ** 
     * find the height of the binary tree through recursion, this way is hard to think 
     * @param node
      * / 
    public  static  int getHeightByRecursion (Node <Integer> node) {
         if (node ​​== null || node == null ) return 0 ;
         intleft = getHeightByRecursion (node.left);
         int right = getHeightByRecursion (node.right);
         if (left> right) {
             return left + 1 ; 
        } else {
             return right + 1 ; 
        } 
    } 

    / ** 
     * Find the binary tree by iteration The height 
     * @param node
      * / 
    public  static  void getHeightByIteration (Node <Integer> node) { 
     // This is the subscript of slow iteration
int front = -1 ;
// This is the subscript at the end of each layer
int last = 0;
//树的高度
int height = 0;
//这个是快迭代的下标
int rear = -1; List<Node<Integer>> linkList = new ArrayList<>(); linkList.add(++rear,node); Node<Integer> node1 = null; while(front < rear){ node1 = linkList.get(++front); if (node1.left != null){ linkList.add(++rear, node1.left); } if (node1.right != null){ linkList.add(++rear, node1.right); } if (front == last){ height++; last = rear; } } System.out.println(height); } public static void main(String[] args) { BinaryTree<Integer> binaryTree = new BinaryTree(); binaryTree.add(7); binaryTree.add(4); binaryTree.add(10); binaryTree.add(9); binaryTree.add(11); binaryTree.add(5); binaryTree.add(3); binaryTree.add(1); binaryTree.add(0); int height = getHeightByRecursion(binaryTree.root); System.out.println(height); getHeightByIteration(binaryTree.root); } }

 

Guess you like

Origin www.cnblogs.com/gunduzi/p/12740903.html