Leetcode::SameTree
同时遍历两个树;
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 stack<TreeNode *> s_p,s_q; 16 17 18 if( !p && ! q) 19 { 20 return true; 21 } 22 else if ( p && q ) 23 { 24 25 while( (p && q ) ||( !s_p.empty()&& ! s_q.empty() )) 26 { 27 if( p && q) 28 { 29 if(p->val != q->val) 30 { 31 return false; 32 } 33 34 s_p.push(p); 35 s_q.push(q); 36 p=p->left; 37 q=q->left; 38 } 39 else if( !p && !q) 40 { 41 p=s_p.top(); 42 q=s_q.top(); 43 s_p.pop(); 44 s_q.pop(); 45 p=p->right; 46 q=q->right; 47 } 48 else 49 { 50 return false; 51 } 52 } 53 54 return true; 55 } 56 else 57 { 58 return false; 59 } 60 61 } 62 }; 63 64
递归实现:
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 if( p == NULL && q == NULL ) 16 { 17 return true; 18 } 19 20 if( p && q ) 21 { 22 if( p->val == q->val ) 23 { 24 return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); 25 } 26 } 27 28 return false; 29 } 30 };