代码随想录算法训练营第十三天| 层序遍历 226.翻转二叉树 (优先掌握递归) 101. 对称二叉树 (优先掌握递归)

层序遍历

注意:

1,使用队列的形式,依次入队,同时对队列进行计数

2,知道数目消失,才进行下一个队列

代码:

 1 vector<vector<int>> levelOrder(TreeNode* root) 
 2 {
 3     vector<vector<int>> result;
 4     if (root == NULL) return result;
 5     queue<TreeNode*> selected;
 6 
 7     selected.push(root);
 8     while (!selected.empty())
 9     {
10         vector<int> valueItem;
11         int nodeCountByLayer = selected.size();
12         while (nodeCountByLayer != 0)
13         {
14             auto top_ = selected.front();
15             selected.pop();
16 
17             valueItem.push_back(top_->val);
18             if (top_->left != NULL) selected.push(top_->left);
19             if (top_->right != NULL) selected.push(top_->right);
20 
21             nodeCountByLayer--;
22         }
23 
24         result.push_back(valueItem);
25     }
26 
27     return result;
28 }

  226.翻转二叉树

代码:

 1 void invert_cursor(TreeNode* node)
 2 {
 3     if (node == NULL) return;
 4     
 5     auto mid = node->left;
 6     node->left = node->right;
 7     node->right = mid;
 8 
 9     invert_cursor(node->left);
10     invert_cursor(node->right);
11 }
12 
13 TreeNode* invertTree_Recursor(TreeNode* root)
14 {
15     if (root == NULL) return root;
16     invert_cursor(root);
17 
18     return root;
19 }

 101. 对称二叉树 

递归:

 1 // 新思路: 使用后续遍历,先迭代的判断,它的左右孩子的外侧是一样的
 2 bool compare_Symetric(TreeNode* left, TreeNode* right)
 3 {
 4     if (!left && right) return false;
 5     else if (left && !right) return false;
 6     else if (left&&right&& left->val != right->val) return false;
 7 
 8     if (!left && !right) return true;
 9     bool out_ = compare_Symetric(left->left, right->right);
10     bool in_ = compare_Symetric(left->right, right->left);
11 
12     return out_ && in_;
13 }
14 bool isSymmetric_1(TreeNode* root) {
15     if (root == NULL) return true;
16 
17     return compare_Symetric(root->left,root->right);
18 }

迭代:

 1 //用栈在实现一下 先进后出,左右中
 2 //思路:先把节点放进去,看他是否存在左右节点不同的情况,如果有直接return false,如果没有,那么进行下面的评判,
 3 //先 r(l) l(r) r(r) l(l)
 4 //这个的解决思路是对单个节点来看它的结果,是错误的,应该看的是
 5 bool isSymmetric(TreeNode* root) {
 6     if (root == NULL) return true;
 7 
 8     stack<TreeNode*> selected;
 9     selected.push(root->left);
10     selected.push(root->right);
11     //注意,这里的左右孩子并不是一个节点的左右孩子,而是随便两个节点
12     while (!selected.empty())
13     {
14         auto l = selected.top(); selected.pop();
15         auto r = selected.top(); selected.pop();
16 
17         if (!l && !r) continue;
18         if ((!l && r) || (l && !r) || (l && r && l->val != r->val))
19         {
20             return false;
21         }
22         
23         //并没有把 l r 加进来
24         selected.push(r->left);
25         selected.push(l->right);
26         selected.push(r->right);
27         selected.push(l->left);
28     }
29     return true;
30 }

 

 

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