求树的深度

题目如下:

随机给定一棵树,求树的深度

思路:

(1)构建一棵树;
(2)将树的根节点作为参数传入方法,判断该节点是否为空,若为空执行return
(3)若不为空,向左递归,直到递归到最下层的左侧的叶子节点;向左递归完成之后,向右递归;
(4)判断left和right哪个更大,树的深度就是大的值加1.

代码如下:

import java.util.*;

public class Test716_05 {
   
	public static void main(String[] args) {
   
		Test716_05 tree = new Test716_05();
		tree.insertDiGui(tree.root,5);
		tree.insertDiGui(tree.root,6);
		tree.insertDiGui(tree.root,3);
		tree.insertDiGui(tree.root,1);
		tree.insertDiGui(tree.root,4);
		tree.insertDiGui(tree.root,9);
		tree.insertDiGui(tree.root,8);
		tree.insertDiGui(tree.root
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个二叉排序树的深度,可以通过递归的方式实现。二叉排序树(BST)的深度等于左子树深度和右子树深度中的较大值再加 1。 下面是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* left; struct node* right; } Node; Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } Node* insert(Node* root, int data) { if (root == NULL) { root = createNode(data); } else if (data <= root->data) { root->left = insert(root->left, data); } else { root->right = insert(root->right, data); } return root; } int maxDepth(Node* root) { if (root == NULL) { return 0; } else { int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return (leftDepth > rightDepth) ? leftDepth + 1 : rightDepth + 1; } } int main() { Node* root = NULL; root = insert(root, 5); insert(root, 3); insert(root, 7); insert(root, 1); insert(root, 9); insert(root, 4); insert(root, 6); printf("The depth of the binary search tree is: %d\n", maxDepth(root)); return 0; } ``` 在这个示例中,我们首先定义了一个 `Node` 结构体来表示二叉排序树的节点,然后定义了 `createNode` 函数来创建一个新的节点,定义了 `insert` 函数来向二叉排序树中插入一个新的节点。 最后,我们使用 `maxDepth` 函数来计算二叉排序树的深度。如果节点为空,返回 0;否则,递归计算左子树和右子树的深度,然后返回左子树深度和右子树深度中的较大值再加 1。 以上代码可以输出以下结果: ``` The depth of the binary search tree is: 4 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值