首页 > 其他分享 >多叉树的高度

多叉树的高度

时间:2023-02-14 15:36:24浏览次数:28  
标签:多叉树 int 高度 tree maxheight public

我们先来回忆一下二叉树的高度问题。

二叉树的高度是由左右子树最高的那一颗来决定的

我们通过分别递归二叉树的左右子树找到最高的那一颗就可以。

 

下图为多叉树:

 

 

 多叉树的高度我们也可以通过递归来解决,只不过多叉树的子树可能很多,那我们只能通过遍历每个节点的字节,并找到同层节点最高的那一颗并返回当前最高的高度就可以了。

 

C# 代码如下

  public class TreeNode
    {
        public int Val { get; set; }
        
        public List<TreeNode>? ChildList { get; set; }

        public TreeNode(int val)
        {
            Val = val;
        }
    }  
  //多叉树的高度
 public int GetMultiwayTreeHeight(TreeNode tree)
        {
            if(tree == null)
            {
                return 0;
            }

            if (tree.ChildList == null)
            {
                return 1;
            }

            int maxheight = int.MinValue;
     //遍历每个节点的子节点,找到最高的高度 foreach(var item in tree.ChildList) { maxheight = Math.Max(GetMultiwayTreeHeight(item) + 1, maxheight); } return maxheight; }

 

标签:多叉树,int,高度,tree,maxheight,public
From: https://www.cnblogs.com/yiming1997/p/17119755.html

相关文章