您的位置:首页 > 娱乐 > 八卦 > 代码随想录算法训练营第十四天| 226.翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、

代码随想录算法训练营第十四天| 226.翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、

2024/10/6 10:28:12 来源:https://blog.csdn.net/qq_43487696/article/details/141599464  浏览:    关键词:代码随想录算法训练营第十四天| 226.翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、

Leetcode 226.翻转二叉树

题目链接:226. 翻转二叉树

C++:(前序遍历)

class Solution {
public:TreeNode* invertTree(TreeNode* root) {//前序遍历if(root == nullptr) return root;swap(root->left, root->right);invertTree(root->left);invertTree(root->right);return root;}
};

Python:(中序遍历)

class Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:if root == None:return rootself.invertTree(root.left)root.left, root.right = root.right, root.leftself.invertTree(root.left)return root

Leetcode101. 对称二叉树

题目链接:101. 对称二叉树

C++:(后序遍历)

class Solution {
public:bool compare(TreeNode* left, TreeNode* right) {// 首先排除空节点的情况if (left == NULL && right != NULL) return false;else if (left != NULL && right == NULL) return false;else if (left == NULL && right == NULL) return true;// 排除了空节点,再排除数值不相同的情况else if (left->val != right->val) return false;// 此时就是:左右节点都不为空,且数值相同的情况// 此时才做递归,做下一层的判断//外结点判断bool outside = compare(left->left, right->right);   // 左子树:左、 右子树:右//内结点判断bool inside = compare(left->right, right->left);    // 左子树:右、 右子树:左bool isSame = outside && inside;                    // 左子树:中、 右子树:中 (逻辑处理)return isSame;}bool isSymmetric(TreeNode* root) {if(root == nullptr) return true;return compare(root->left, root->right);}
};

Leetcode104.二叉树的最大深度

题目链接:104. 二叉树的最大深度

C++:(后序遍历)

class Solution {
public:int maxDepth(TreeNode* root) {if (root == NULL) return 0;int leftdepth = maxDepth(root->left);       // 左int rightdepth = maxDepth(root->right);     // 右int depth = 1 + max(leftdepth, rightdepth); // 中return depth;}
};

Leetcode111.二叉树的最小深度

题目链接:111. 二叉树的最小深度

C++:(后序遍历)

class Solution {
public:int minDepth(TreeNode* root) {if(root == nullptr) return 0;int leftdepth = minDepth(root->left);int rightdepth = minDepth(root->right);if(root->left == nullptr && root->right != nullptr)return 1 + rightdepth;if(root->left != nullptr && root->right == nullptr)return 1 + leftdepth;int depth = 1 + min(leftdepth, rightdepth);return depth;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com