2023每日刷题(十八)
Leetcode—100.相同的树
递归实现代码
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {if(p == NULL && q == NULL) {return true;}if((!p && q) || (p && !q)) {return false;}if(p->val != q->val) {return false;}if(isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) {return true;}return false;
}
运行结果
先序序列化实现代码
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/#define nulll -1class Solution {
public:void preorderseq(TreeNode* b, vector<int> &pre) {if(b) {// 根pre.push_back(b->val);// 左preorderseq(b->left, pre);// 右preorderseq(b->right, pre);} else {pre.push_back(nulll);}}bool isSameTree(TreeNode* p, TreeNode* q) {if(p == nullptr && q == nullptr) {return true;}if((!p && q) || (p && !q)) {return false;}vector<int> pre1, pre2;preorderseq(p, pre1);preorderseq(q, pre2);if(pre1.size() != pre2.size()) {return false;}for(int i = 0; i < pre1.size(); i++) {if(pre1[i] != pre2[i]) {return false;}}return true;}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!