DAY12 二叉树part02
今日任务
二叉树的对称性
翻转二叉树
二叉树的最大/小深度(递归法)
226.翻转二叉树 (优先掌握递归)
题目链接/文章讲解/视频讲解:https://programmercarl.com/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.html
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* invertTree(TreeNode* root) { 15 if(root==nullptr) return root; 16 swap(root->left,root->right); 17 invertTree(root->left); 18 invertTree(root->right); 19 return root; 20 } 21 };
101. 对称二叉树 (优先掌握递归)
题目链接/文章讲解/视频讲解:https://programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 bool isSymmetric(TreeNode* root) { 15 if(root==nullptr) return true; 16 else return comtree(root->left,root->right); 17 } 18 bool comtree(TreeNode* right,TreeNode* left) 19 { 20 if(right==nullptr&&left==nullptr) return true; 21 else if(right!=nullptr&&left==nullptr) return false; 22 else if(right==nullptr&&left!=nullptr) return false; 23 else if(right->val!=left->val) return false; 24 else return comtree(left->right,right->left)&&comtree(left->left,right->right); 25 } 26 };
104.二叉树的最大深度 (优先掌握递归)
题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int maxDepth(TreeNode* root) { 15 if(root==nullptr) return 0; 16 int leftd=maxDepth(root->left); 17 int rightd=maxDepth(root->right); 18 int depth=1+max(leftd,rightd); 19 return depth; 20 } 21 };
111.二叉树的最小深度 (优先掌握递归)
题目链接/文章讲解/视频讲解:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html
1 class Solution { 2 public: 3 int minDepth(TreeNode* root) { 4 if(root==NULL) return 0; 5 int leftd=minDepth(root->left); 6 int rightd=minDepth(root->right); 7 int depth=0; 8 if(leftd==0&&rightd!=0) depth=1+rightd; 9 else if(rightd==0&&leftd!=0) depth=1+leftd; 10 else depth=1+min(leftd,rightd); 11 return depth; 12 13 } 14 };
递归一遍反正写不明白,抽时间再写写吧