数据结构——求树的最大深度或者树高

原文地址:Write a Program to Find the Maximum Depth or Height of a Tree

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


这里写图片描述

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

算法:

maxDepth()
1. 如果树为空,那么返回0
2. 否则
     (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 node
class 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) 。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值