递归算法:求二叉树的深度

  • 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
  • 采用先序遍历的方法,计算每一条路径的长度,取最大路径。
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
    int depth=0;
    int count=0;
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==NULL)
            return 0;
         return getDep(pRoot);
    }
    int getDep(TreeNode* pRoot)
    {
        if(pRoot==NULL)
            return 0;
        if(pRoot)
        {
            count++;
            getDep(pRoot->left);
            if(count>depth)
                depth=count;
            getDep(pRoot->right);
            count--;
        }
        return depth;
    }
};

在这里插入图片描述

### 使用递归算法二叉树高度的解决方案 递归算法是一种常用的方法来计算二叉树的高度。其核心思想是通过递归调用分别计算左子树和右子树的高度,然后取两者中的较大值并加1作为当前节点的高度[^1]。 以下是具体的实现代码示例: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def treeDepth(root: TreeNode) -> int: if root is None: # 如果当前节点为空,则返回高度为0 return 0 left_depth = treeDepth(root.left) # 递归计算左子树的高度 right_depth = treeDepth(root.right) # 递归计算右子树的高度 return max(left_depth, right_depth) + 1 # 返回左右子树中较大的高度加1 ``` 上述代码定义了一个 `treeDepth` 函数,用于计算给定二叉树的高度。如果根节点为空,则直接返回高度为0;否则,递归计算左子树和右子树的高度,并返回两者的最大值加1[^2]。 #### 示例说明 假设有一棵如下结构的二叉树: ``` 1 / \ 2 3 / / \ 4 5 6 ``` 创建该树的代码如下: ```python root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.left = TreeNode(5) root.right.right = TreeNode(6) ``` 调用 `treeDepth(root)` 后,将返回树的高度为3,因为从根节点到最深的叶子节点(如节点4或节点6)的距离为3。 --- ### 非递归方法(基于队列) 除了递归方法外,还可以使用队列实现非递归版本的二叉树高度计算。这种方法利用广度优搜索(BFS)的思想逐层遍历二叉树,并记录层数以得到树的高度[^4]。 ```python from collections import deque def getTreeHeight(root: TreeNode) -> int: if root is None: # 如果根节点为空,则返回高度为0 return 0 queue = deque([(root, 1)]) # 初始化队列,存储节点及其对应的深度 max_depth = 0 while queue: node, depth = queue.popleft() # 弹出队首元素 max_depth = max(max_depth, depth) # 更新最大深度 if node.left: queue.append((node.left, depth + 1)) # 将左子节点入队,并增加深度 if node.right: queue.append((node.right, depth + 1)) # 将右子节点入队,并增加深度 return max_depth ``` --- ### 总结 递归方法简单直观,适合处理中小规模的二叉树。对于大规模二叉树,非递归方法更为安全,因为它避免了递归深度过大导致的栈溢出问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值