求二叉树的高度

求二叉树高度的思路非常简单,类似于二叉树的层次遍历。用一个队列来保存二叉树某一层的结点,判断此队列是否为空,若为空,说明上一层没有子结点,即可结束程序;否则,先得到此队列的长度,依次将上层结点出队列,同时将每个结点的左右孩子(如果有)入队,重复此过程即可。

import java.util.*;
/*结点类
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
*/
public class Solution {
    public int maxDepth(TreeNode root) {
        int depth=0;
        if(root == null)
            return 0;
        LinkedList list = new LinkedList();
        //根结点入队,初始化队列
        list.offer(root);
        //每一次循环结束后,队列里所有结点同属同一层
        while(list.size() != 0){
            //队列不为空,则高度加一
            depth++;
            //本层结点个数
            int size = list.size();
            //将本层结点依次出队并将孩子入队得到下一层的所有结点
            for(int i=0; i<size; i++){
                TreeNode e = (TreeNode)list.poll();
                if(e.left!=null)
                    list.offer(e.left);
                if(e.right!=null)
                    list.offer(e.right);
            }
        }
        return depth;
    }
}

递归方式:

public int maxDepth(TreeNode root){
    if(root==null)
        return 0;
    int lDepth = maxDepth(root.left);
    int rDepth = maxDepth(root.right);
    return 1+(lDepth>rDepth?lDepth:rDepth);
}
### C语言实现二叉树高度的方法 在C语言中,可以通过递归的方式计算二叉树高度。以下是具体的实现方法: #### 定义二叉树结构 首先需要定义一个表示二叉树节点的结构体 `tree`,该结构体包含三个成员变量:一个是用于存储数据的数据域 `data`;另外两个是指向左孩子和右孩子的指针 `lchild` 和 `rchild`。 ```c typedef struct node { int data; struct node* lchild; struct node* rchild; } tree; ``` #### 计算二叉树高度的函数 为了计算二叉树高度,可以设计如下递归函数 `BTreeHeight` 来完成此任务。如果当前节点为空,则返回高度为 0;否则分别递归计算其左子树和右子树的高度,并取两者中的较大值加一作为最终结果[^4]。 ```c int BTreeHeight(tree* root) { if (root == NULL) { return 0; } int left = BTreeHeight(root->lchild); int right = BTreeHeight(root->rchild); return (left > right) ? (left + 1) : (right + 1); } ``` 上述代码片段展示了如何利用递归来获取一棵给定根节点的二叉树的最大深度即所谓的“高度”。当遇到空节点时停止进一步深入探索并回溯至父级调用处,逐步累积得到整棵树的实际层数信息[^3]。 ### 示例程序 下面给出完整的示例代码,展示如何构建一颗简单的二叉树以及调用上面提到过的函数去测量它的高度: ```c #include <stdio.h> #include <stdlib.h> // Define the structure for a binary tree node. typedef struct node { int data; struct node* lchild; struct node* rchild; } tree; // Function prototypes declaration. tree* createTreeNode(int value); void destroyTree(tree* t); int calculateBinaryTreeHeight(tree* root); // Main function demonstrating usage of our functions. int main() { // Create sample nodes forming part of a small binary search tree. tree* root = createTreeNode(1); root->lchild = createTreeNode(2); root->rchild = createTreeNode(3); root->lchild->lchild = createTreeNode(4); root->lchild->rchild = createTreeNode(5); printf("The height of this binary tree is %d.\n", calculateBinaryTreeHeight(root)); // Clean up memory before exiting program execution flow completely. destroyTree(root); return EXIT_SUCCESS; } /** * Helper method used internally within other methods but exposed here so it can be reused elsewhere too as needed later on potentially depending upon use case requirements etc... */ tree* createTreeNode(int value){ tree* newNode=(tree*)malloc(sizeof(struct node)); newNode->data=value; newNode->lchild=NULL; newNode->rchild=NULL; return(newNode); } /** * Recursive helper routine responsible primarily towards freeing all dynamically allocated resources associated with each individual element present inside given input parameter 't'. */ void destroyTree(tree* t){ if(t!=NULL){ destroyTree(t->lchild); destroyTree(t->rchild); free(t); } } /** Calculates and returns the maximum depth/height from current position downwards recursively until reaching leaf level where no more children exist anymore.*/ int calculateBinaryTreeHeight(tree* root){ if(!root){return 0;} int leftSubtreeDepth=calculateBinaryTreeHeight(root->lchild); int rightSubtreeDepth=calculateBinaryTreeHeight(root->rchild); return ((leftSubtreeDepth>rightSubtreeDepth)?leftSubtreeDepth:rightSubtreeDepth)+1; } ``` 问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值