迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: bool isSubStructure(TreeNode* A, TreeNode* B) { if(!B || !A) return false; if(A->val == B->val && helper(A->left, B->left) && helper(A->right, B->right)) return true; return isSubStructure(A->left, B) || isSubStructure(A->right, B); } private: bool helper(TreeNode* A, TreeNode* B) { if(!B) return true; if(!A) return false; if(A->val != B->val) return false; return helper(A->left, B->left) && helper(A->right, B->right); }
};
|
遍历树,碰到A中值和B根相同的点就去递归判断是不是相同子树
情况如下
- 当A为空B非空,则
false
- 当B为空A非空,则便利结束,为
true
- 当A值!=B值,则
false
- A值==B值,继续判断