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

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 }

 

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

后续遍历:

 1 int minD_cursor_after(TreeNode* node)
 2 {
 3     int result = 0;
 4     if (!node) return 0;
 5 
 6     if (node->left && !node->right) result = 1 + minD_cursor_after(node->left);
 7     else if (node->right && !node->left) result = 1 + minD_cursor_after(node->right);
 8     else result = 1 + min(minD_cursor_after(node->left), minD_cursor_after(node->right));
 9 
10     return result;
11 }

前序遍历

 1 void minD_cursor(TreeNode* node, int& result)
 2 {
 3     if (!node) return;
 4 
 5     result += 1;
 6     if (node->left && !node->right) minD_cursor(node->left, result);
 7     else if (!node->left && node->right) minD_cursor(node->right, result);
 8     else {
 9         int left = 0;
10         minD_cursor(node->left, left);
11         int right = 0;
12         minD_cursor(node->right, right);
13         result += min(left, right);
14     }
15 }

 222.完全二叉树的节点个数(优先掌握递归)

迭代法:层序遍历

 1 int countNodes(TreeNode* root) {
 2     int result = 0;
 3     if (!root) return result;
 4     queue<TreeNode*> selected;
 5     selected.push(root);
 6     while (!selected.empty())
 7     {
 8         int i = selected.size();
 9         result += selected.size();
10         while (i != 0)
11         {
12             auto cur_ = selected.front();
13             selected.pop();
14 
15             if (cur_->left) selected.push(cur_->left);
16             if (cur_->right) selected.push(cur_->right);
17             i--;
18         }
19     }
20 
21     return result;
22 }

递归法

思路:

终止条件:

1,如果是完全二叉树,那么返回2^n-1 代码: (2<<n)-1

2,如果是空节点,那么0

普通节点,就是按照以前的遍历方式,1+左+右

学习的地方:

可以自定义一个中止节点,这样可以减少遍历的次数

代码:

 1 int count_cur(TreeNode* node)
 2 {
 3     if (!node) return 0;
 4     //如果是满差数,直接返回所有的数目
 5     int r=0, l = 0;
 6     TreeNode *lN = node->left,*rN = node->right;
 7     while (lN)
 8     {
 9         l++;
10         lN = lN->left;
11     }
12     while (rN)
13     {
14         r++;
15         rN = rN->right;
16     }
17     if (r == l) return (2 << l) - 1;
18 
19     return 1 + count_cur(node->left) + count_cur(node->right);
20 }
21 int countNodes_cursor(TreeNode* root) {
22     int result = 0;
23     result = count_cur(root);
24 
25     return result;
26 }

 

posted @ 2023-06-22 10:22  博二爷  阅读(1)  评论(0编辑  收藏  举报