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.
不用解释吧。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSameTree(TreeNode *p, TreeNode *q) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 queue<TreeNode*> q1; 16 queue<TreeNode*> q2; 17 q1.push(p); 18 q2.push(q); 19 while(!q1.empty()) 20 { 21 TreeNode * tmp1 = q1.front(); 22 TreeNode * tmp2 = q2.front(); 23 q1.pop(); 24 q2.pop(); 25 if(tmp1 == NULL && tmp2 == NULL) 26 continue; 27 if(tmp1 == NULL || tmp2 == NULL) 28 return false; 29 if(tmp1->val != tmp2->val) 30 return false; 31 q1.push(tmp1->left); 32 q1.push(tmp1->right); 33 q2.push(tmp2->left); 34 q2.push(tmp2->right); 35 } 36 return true; 37 } 38 };

浙公网安备 33010602011771号