当前位置: 首页> 健康> 美食 > 9.13 DFSBFS 简单 101 Symmetric Tree 104 Maximum Depth of Binary Tree

9.13 DFSBFS 简单 101 Symmetric Tree 104 Maximum Depth of Binary Tree

时间:2025/7/31 3:19:24来源:https://blog.csdn.net/emmm_Yeah/article/details/142215468 浏览次数:0次

101 Symmetric Tree

在这里插入图片描述

class Solution {
public:// 比较两个向量是否镜像对称bool isIdentical(const std::vector<int>& n1, const std::vector<int>& n2) {int n = n1.size();for (int i = 0; i < n; i++) {if (n1[i] != n2[n - i - 1]) return false;  // 镜像对应的元素比较}return true;}bool isSymmetric(TreeNode* root) {if (!root) return true;//出现的问题:左右子树的入队顺序、对负值和nullptr的区分// 使用queue来进行层次遍历queue<TreeNode*> prev;prev.push(root);while (!prev.empty()) {std::vector<int> curr;int size = prev.size();// 遍历当前层的所有节点for (int i = 0; i < size; i++) {TreeNode* node = prev.front();prev.pop();if (node) {curr.push_back(node->val);   // 当前节点值prev.push(node->left);       // 左子节点入队prev.push(node->right);      // 右子节点入队} else {curr.push_back(INT_MIN);     // 用INT_MIN来表示null节点}}// 检查当前层是否镜像对称if (!isIdentical(curr, curr)) {return false;}}return true;}
};

104 Maximum Depth of Binary Tree

在这里插入图片描述

class Solution {
public:int DFS(TreeNode* node, int height) {// 如果当前节点为空,返回当前高度if (!node) return height;// 如果是叶子节点,返回当前高度+1if (!node->left && !node->right) {return height + 1;}// 递归计算左右子树的最大高度,返回其中的较大值int leftHeight = DFS(node->left, height + 1);int rightHeight = DFS(node->right, height + 1);// 返回左右子树的最大高度return max(leftHeight, rightHeight);}int maxDepth(TreeNode* root) {// 深度搜索DFS,从高度0开始return DFS(root, 0);}
};
关键字:9.13 DFSBFS 简单 101 Symmetric Tree 104 Maximum Depth of Binary Tree

版权声明:

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

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

责任编辑: