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() + "  ");
            }
        }

  • 相关阅读:
    xml
    企业级应用和互联网应用的区别
    javaee学习目标
    数据库基本原理
    数据库学习感想
    数据库设计
    团队项目自我评价
    团队项目-软件度量
    团队项目-初级版本
    团队项目—详细设计
  • 原文地址:https://www.cnblogs.com/rodge-run/p/8108648.html
Copyright © 2011-2022 走看看