博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构——求树的最大深度或者树高
阅读量:4099 次
发布时间:2019-05-25

本文共 2319 字,大约阅读时间需要 7 分钟。

原文地址:

已知一个二叉树,求它的高。空树的树高是0,下面的树的树高是3。

这里写图片描述

递归地计算一个节点的左右子树的树高,将高度设值为两个孩子最大高度加1。看下面的伪代码和程序的详细情况。

算法:

maxDepth()1. 如果树为空,那么返回02. 否则     (a) 递归得到左子树的最大高度    例如,调用maxDepth( tree->left-subtree)     (b) 递归得到右子树的最大高度    例如,调用maxDepth( tree->right-subtree)     (c) 对于当前节点,取左右子树高度的最大值并加1。         max_depth = max(左子树的最大高度, 右子树的最大高度) + 1     (d) 返回max_depth

下图是对于上面树的例子更清楚地说明了递归函数maxDepth()的执行。

maxDepth('1') = max(maxDepth('2'), maxDepth('3')) + 1                               = 2 + 1                                  /    \                                /         \                              /             \                            /                 \                          /                     \               maxDepth('1')                  maxDepth('3') = 1= max(maxDepth('4'), maxDepth('5')) + 1= 1 + 1   = 2                            /    \                 /        \               /            \             /                \           /                    \ maxDepth('4') = 1     maxDepth('5') = 1

实现:

// Java program to find height of tree// A binary tree nodeclass Node {    int data;    Node left, right;    Node(int item)     {        data = item;        left = right = null;    }}class BinaryTree {     Node root;    /* Compute the "maxDepth" of a tree -- the number of        nodes along the longest path from the root node        down to the farthest leaf node.*/    int maxDepth(Node node)     {        if (node == null)            return 0;        else        {            /* compute the depth of each subtree */            int lDepth = maxDepth(node.left);            int rDepth = maxDepth(node.right);            /* use the larger one */            if (lDepth > rDepth)                return (lDepth + 1);             else                return (rDepth + 1);        }    }    /* Driver program to test above functions */    public static void main(String[] args)     {        BinaryTree tree = new BinaryTree();        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        System.out.println("Height of tree is : " +                                       tree.maxDepth(tree.root));    }}// This code has been cpontributed by Mayank Jaiswal(mayank_24)

时间复杂度: O(n) 。

你可能感兴趣的文章
大文件分组上传以及进度条
查看>>
python字符串与时间互相转换
查看>>
HttpResponse和HttpResquest与会话技术
查看>>
前端页面上传文件夹的方法
查看>>
前端页面上传多文件与后台接收
查看>>
查看线上服务器日志
查看>>
怎么高效率批量插入1000条数据到数据库
查看>>
多图片上传后在前端展示
查看>>
js判断上传文件为图片格式、excel格式
查看>>
对上传文件的展示、增删重选功能(前后端代码)
查看>>
python实现八大排序
查看>>
gevent并发查询域名
查看>>
linux常见目录说明
查看>>
基础库httplib2
查看>>
基于Django、WeRoBot的微信公众平台开发(一)
查看>>
基于Django、WeRoBot的微信公众平台开发(二)
查看>>
基于Django、WeRoBot的微信公众平台开发(二) - 后续
查看>>
使用haystack实现django全文检索搜索引擎功能
查看>>
go的简单并发之goroutine与WaitGroup
查看>>
结构体、通道、并发实现生产者消费者
查看>>