求二叉樹的高度【Java】


概述

  遍歷二叉樹在上一篇文章中已經講過了,那如何求一顆二叉樹的高度呢?這一講就講這個問題。

思路

  其實這個思路很難說清楚,大致的意思就是每遍歷一層就把高度加1,那問題來了,怎么判斷我這一層遍歷結束了呢?這個可以通過記錄每一層的個數,然后當把這一層的每一個都遍歷之后就說明這一層遍歷完了,那問題又來了,怎么記錄每一層的個數呢?這個就有技巧了,思路是這樣的,使用兩個遍歷同時進行,第一個遍歷遍歷下一層的時候,第二個遍歷遍歷上一層,當上一層遍歷完的時候,下一層也就遍歷完了,然后在這個過程中就可以通過一些標志位來讓高度加1.

  可能看了上面的思路更加迷糊了,下面直接看代碼吧。

基礎代碼,就是二叉樹的構成和每個節點的代碼。

二叉樹:

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) {
        //這種方式就是匿名內部類,通過給一個類傳一個接口作為參數,然后這個通過一個匿名內部類是實現這個接口來傳入實現。
        BinaryTree<Integer> binaryTree = new BinaryTree<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return 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

節點:

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

判斷二叉樹的高度

package com.example.demo.tree;

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

/**
 * @author steve
 * @date 2020/4/20 6:36 下午
 * @description 求出二叉樹的高度,通過遞歸和迭代的方式實現
 */
public class BinaryTreeHeight {

    /**
     * 通過遞歸的方式求出二叉樹高度,這種方式很難想
     * @param node
     */
    public static int getHeightByRecursion(Node<Integer> node){
        if (node == null || node == null) return 0;
        int left = getHeightByRecursion(node.left);
        int right = getHeightByRecursion(node.right);
        if (left > right){
            return left + 1;
        }else {
            return right + 1;
        }
    }

    /**
     * 通過迭代求出二叉樹的高度
     * @param node
     */
    public static void getHeightByIteration(Node<Integer> node){
     //這個就是慢迭代的下標
int front = -1;
//這個是記錄每一層結尾處的下標
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); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM