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

  • 相关阅读:
    webpack learn2-vue的jsx写法和postcss 1
    浏览器缓存旧的js文件或css文件导致没出现预期效果
    webpack learn1-webpack-dev-server的配置和使用3
    Python正课60 —— configparser模块
    Python正课59 —— json与pickle模块
    Python正课58 —— 小说阅读项目 初级
    Python正课57 —— ATM+购物车 前戏
    Python正课56 —— shutil模块
    Python正课55 —— sys模块
    Python正课54 —— os模块
  • 原文地址:https://www.cnblogs.com/rodge-run/p/8108648.html
Copyright © 2011-2022 走看看