求树的深度

题目描述

  输入一棵二叉树,求该树的深度。
  从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
来自牛客。
 1     public int TreeDepth(TreeNode root) {
 2         //递归实现
 3         /*if(root == null){
 4             return 0;
 5         }
 6         int leftcount = TreeDepth(root.left);
 7         int rightcount = TreeDepth(root.right);
 8         //如果左右子节点都为空,返回0,0再加当前节点1
 9         return Math.max(leftcount , rightcount)+1;
10         */
11         if(root == null) return 0;
12         LinkedList<TreeNode> list = new LinkedList<TreeNode>();
13         list.add(root);
14         //depth为深度,什么情况下深度会加1呢?当把当前这一层所有节点都pop完就进入下一层
15         //那怎么确定计算完当前节点呢?cur累加至当层左右节点pop完,即cur==nextcount
16         int depth = 0,curCount = 0,nextCount = list.size();
17         while(!list.isEmpty()){
18             TreeNode curTree = list.pop();
19             curCount++;
20             if(curTree.left != null){
21                 list.add(curTree.left);
22             }
23             if(curTree.right != null){
24                 list.add(curTree.right);
25             }
26             if(curCount == nextCount){
27                 curCount = 0;
28                 nextCount = list.size();
29                 depth++;
30             }
31         }
32         return depth;
33 
34 
35     }

 

转载于:https://www.cnblogs.com/blog-of-zxf/p/11395632.html

要求一个二叉排序树的深度,可以通过递归的方式实现。二叉排序树(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、付费专栏及课程。

余额充值