• 二叉树的遍历


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

  • 相关阅读:
    轻重搭配
    EF的优缺点
    使用bootstrap-select有时显示“Nothing selected”
    IIS发布 HTTP 错误 500.21
    js添加的元素无法触发click事件
    sql server查看表是否死锁
    sql server把一个库表的某个字段更新到另一张表的相同字段
    SQLSERVER排查CPU占用高的情况
    SQL server中如何按照某一字段中的分割符将记录拆成多条
    LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.
  • 原文地址:https://www.cnblogs.com/rodge-run/p/8108648.html
Copyright © 2020-2023  润新知