递归方法和迭代方法,下面分别给出C语言和C#语言的实现示例。

(图片来源网络,侵删)
C语言实现
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int max(int a, int b) {
return (a > b) ? a : b;
}
int getDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftDepth = getDepth(root>left);
int rightDepth = getDepth(root>right);
return max(leftDepth, rightDepth) + 1;
}
int main() {
// 创建一个简单的二叉树进行测试
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root>val = 1;
root>left = (TreeNode*)malloc(sizeof(TreeNode));
root>left>val = 2;
root>right = (TreeNode*)malloc(sizeof(TreeNode));
root>right>val = 3;
root>left>left = NULL;
root>left>right = NULL;
root>right>left = NULL;
root>right>right = NULL;
printf("The depth of the binary tree is: %dn", getDepth(root));
// 释放内存
free(root>left);
free(root>right);
free(root);
return 0;
}
C#语言实现
using System;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public int GetDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = GetDepth(root.left);
int rightDepth = GetDepth(root.right);
return Math.Max(leftDepth, rightDepth) + 1;
}
}
public class Program {
public static void Main() {
// 创建一个简单的二叉树进行测试
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = null;
root.left.right = null;
root.right.left = null;
root.right.right = null;
Solution solution = new Solution();
Console.WriteLine("The depth of the binary tree is: " + solution.GetDepth(root));
}
}
相关问题与解答:
1、问题:如果二叉树中存在环,如何计算其深度?
答案:在计算二叉树深度时,我们假设二叉树是无环的,如果存在环,那么这个问题就变得复杂了,因为我们需要检测环的存在并处理它,一种常见的方法是使用快慢指针法来检测环,并在检测到环时停止计算深度。

(图片来源网络,侵删)
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!