zoukankan      html  css  js  c++  java
  • 二叉树算法

    二叉树算法

    二叉树中树节点的数据结构

    二叉树由一系列树结点组成,每个结点包括三个部分:一个是存储数据元素的数据域,另一个是存储左子结点地址的指针域,另一个是存储右子结点地址的指针域。

    定义树节点为类:TreeNode。具体实现如下:

    public class TreeNode {
    
        public int val; // 数据域
        public TreeNode left; // 左子树根节点
        public TreeNode right; // 右子树根节点
    
        public TreeNode() {
    
        }
    
        public TreeNode(int val) {
            this.val = val;
        }
    
    }
    

    递归解法

    **
     * 1. 前序遍历
     * 递归
     * @param tree树根节点
     */
    public static void TreeNodeShow(TreeNode tree){
       if (tree== null) {
           return;
       }
       System.out.print(tree.val + "->");
       TreeNodeShow(tree.left);
       TreeNodeShow(tree.right);
    }
    

    中序遍历、后序遍历都一样

    求二叉树中的节点个数

    递归解法

    /**
     * 1. 求二叉树中的节点个数
     * 递归
     * @param tree 树根节点
     * @return 节点个数
     */
    public static int getTreeNode(TreeNode tree) {
        if (tree== null) {
            return 0;
        }
        return getTreeNode(tree.left) + getTreeNode(tree.right) + 1;
    }
    

     求二叉树的深度(高度)

    递归解法

    /**
    * 求二叉树的深度(高度) 
    * 递归
    * @return 树的深度
    */
    public static int getTreeNodeLong(TreeNode tree) {
       if (tree== null) {
           return 0;
       }
       return Math.max(getTreeNodeLong(tree.left), getTreeNodeLong(root.tree)) + 1;
    

    就学了这些简单的,如果你想深入学习可以https://blog.csdn.net/u012428012/article/details/79089915到这位大佬那去学习

      

  • 相关阅读:
    smith waterman算法
    深度复数网络 Deep Complex Networks
    生成对抗网络 Generative Adversarial Networks
    dl +rec
    python 后台运行命令
    conversion vs recommendation
    激活pycharm
    keras 自定义 custom 函数
    keras 保存训练的最佳模型
    python memory-management
  • 原文地址:https://www.cnblogs.com/mvpbest/p/13272039.html
Copyright © 2011-2022 走看看