代码随想录算法训练营第十四天| 104.二叉树的最大深度 (优先掌握递归) 111.二叉树的最小深度 (优先掌握递归) 222.完全二叉树的节点个数(优先掌握递归)

发布时间 2023-06-22 10:26:57作者: 博二爷

104.二叉树的最大深度 (优先掌握递归)

迭代法,上一篇已经讲过,只需要对每一层+1,这里重要些递归法

递归法注意:如果当前节点为NULL,返回0,不是NULL,那么就是 1+ max(right,left)

代码:

 1 void maxD_cursor(TreeNode* node, int& result)
 2 {
 3     if (!node) return;
 4 
 5     result += 1;
 6     int leftDepth = 0;
 7     int rightDepth = 0;
 8     maxD_cursor(node->left, leftDepth);
 9     maxD_cursor(node->right, rightDepth);
10 
11     result += leftDepth > rightDepth ? leftDepth : rightDepth;
12 }
13 
14 int maxDepth_cursor(TreeNode* root) {
15     int result = 0;
16     maxD_cursor(root, result);
17 
18     return result;
19 }