zoukankan      html  css  js  c++  java
  • 二叉树的遍历

    1. 二叉树基础知识

      二叉树是每个节点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。二叉树常被用于实现二叉查找树和二叉堆。

      对于一颗深度为h的二叉树, 其最多有2^h-1个节点, 第h层最多有2^(h-1)个节点;

      满二叉树: 一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是满二叉树。满二叉树有2^h-1个节点;

      完全二叉树, 若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。完全二叉树的节点范围:2^(h-1)-1 < o(h) <= 2^h-1;(满二叉树可以看成是完全二叉树的一个特例)

    2. 二叉树的遍历

    public class BinaryTree {
        private BinaryTree leftNode;
        private BinaryTree rightNode;
        private Character data;

    ...

    }

      2.1前序遍历(根-左-右)

      //前序遍历:根-左-右
        public static void preOrder(BinaryTree tree) {
            if (tree != null) {
                System.out.print(tree.getData() + "  ");
                if (tree.getLeftNode() != null) {
                    preOrder(tree.getLeftNode());
                }
                if (tree.getRightNode() != null) {
                    preOrder(tree.getRightNode());
                }
            }
        }

      2.2中序遍历(左-根-右)

      //中序遍历:左-根-右
        public static void midOrder (BinaryTree tree) {
            if (tree != null) {
                if (tree.getLeftNode() != null) {
                    midOrder(tree.getLeftNode());
                }
                System.out.print(tree.getData() + "  ");
                if (tree.getRightNode() != null) {
                    midOrder(tree.getRightNode());
                }
            }
        }

      2.3后续遍历(左-右-根)

      //后续遍历:左-右-根
        public static void postOrder (BinaryTree tree) {
            if (tree != null) {
                if (tree.getLeftNode() != null) {
                    postOrder(tree.getLeftNode());
                }
                if (tree.getRightNode() != null) {
                    postOrder(tree.getRightNode());
                }
                System.out.print(tree.getData() + "  ");
            }
        }

  • 相关阅读:
    dubbo总结
    搞懂分布式技术28:微服务(Microservice)那点事
    搞懂分布式技术21:浅谈分布式消息技术 Kafka
    搞懂分布式技术20:消息队列因何而生
    搞懂分布式技术19:使用RocketMQ事务消息解决分布式事务
    搞懂分布式技术17,18:分布式事务总结
    热敏电阻
    eagle学习汇总
    CSS浮动通俗讲解
    总结一下CSS定位
  • 原文地址:https://www.cnblogs.com/rodge-run/p/8108648.html
Copyright © 2011-2022 走看看