相同的树
和101对称二叉树类似
/** * 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) {} * }; */ class Solution { public: bool compare(TreeNode* p, TreeNode* q) { if(p == nullptr && q == nullptr) return true; else if(p != nullptr && q == nullptr) return false; else if(p == nullptr && q != nullptr) return false; if(p->val != q->val) return false; bool left_val = compare(p->left , q->left); bool right_val = compare(p->right , q->right); return left_val & right_val; } bool isSameTree(TreeNode* p, TreeNode* q) { return compare(p,q); } };
二刷
/** * 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) {} * }; */ class Solution { public: bool track_back(TreeNode* p, TreeNode* q) { if(p==nullptr && q==nullptr) return true; else if(p != nullptr && q == nullptr) return false; else if(p == nullptr && q != nullptr) return false; if(p->val != q->val ) return false; bool left_bool = track_back(p->left , q->left); bool right_bool = track_back(p->right , q->right); return left_bool&right_bool ; } bool isSameTree(TreeNode* p, TreeNode* q) { return track_back(p,q); } };