标签:
/// 找到相同结点后,判断子树是否相同,判断子树是否相同时,采用了非递归算法(深度优先)
/// 一个小问题:B为空时,是否也算是A的子结构呢?
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: bool HasSubtree(TreeNode* A, TreeNode* B) { if(!B)return false; if(!A)return false; bool res = false; if(A->val == B->val){ res = compareSub(A,B); } if(res){ return true; } else { return HasSubtree(A->left,B)||HasSubtree(A->right,B); } } bool compareSub(TreeNode* X, TreeNode* B){ stack<TreeNode* >stk; stack<TreeNode* >stk2; stk.push(X); stk2.push(B); while(!stk2.empty()){ TreeNode* n = stk.top(); TreeNode* n2 = stk2.top(); if(n->val != n2->val){ return false; } stk.pop(); stk2.pop(); if(n2->right){ if(n->right) stk.push(n->right); else return false; stk2.push(n2->right); } if(n2->left){ if(n->left) stk.push(n->left); else return false; stk2.push(n2->left); } } return true; } };
标签:
原文地址:http://www.cnblogs.com/numclock/p/4691055.html