Same Tree
Total Accepted: 56263 Total Submissions: 133912My Submissions
Question Solution
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Hide Tags
Have you met this question in a real interview?
Yes
No
#include<iostream> #include<vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; //这样做可以AC,但是有点问题,将两个树都采用先序遍历,将遍历结果都存入到 //vector中,然后比较两个vector,而在这中间有个问题就是在空的结点出我存的是‘#‘,而 //转化为asii码,但这有点问题的 void first_search(TreeNode* root,vector<int>& vec) { if(root!=NULL) vec.push_back(root->val); else {vec.push_back(‘#‘);return;} first_search(root->left,vec); first_search(root->right,vec); return; } bool isSameTree(TreeNode *p, TreeNode *q) { vector<int> vec1,vec2; first_search(p,vec1); first_search(q,vec2); if(vec1==vec2) return 1; else return 0; } int main() { }
时间: 2024-11-05 12:15:39