二叉树深度
二叉树深度
1、题目
2、题解
方法1:递归
思路:如果结点存在则返回结点左右子树深度的最大值加1(\(root_{depth}=max(left_{depth},right_{depth})+1\)),如果
左右子树为空则返回0。
代码实现:
1 | |
方法2:层遍历
思路:遍历每层的结点,用队列对结点进行存储。每次存储下一层结点时,深度加1。
代码实现:
1 | |
二叉树深度
http://example.com/2023/10/20/Tree-depth/
思路:如果结点存在则返回结点左右子树深度的最大值加1(\(root_{depth}=max(left_{depth},right_{depth})+1\)),如果
左右子树为空则返回0。
代码实现:
1 | |
思路:遍历每层的结点,用队列对结点进行存储。每次存储下一层结点时,深度加1。
代码实现:
1 | |