输入两棵二叉树 A,BA,B,判断 BB 是不是 AA 的子结构。
我们规定空树不是任何树的子结构。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool dfs (TreeNode* a, TreeNode* b) { if (!b) return true; if (!a) return false; if (a->val != b->val) return false; return dfs (a->left, b->left) && dfs (a->right, b->right) ; } bool hasSubtree(TreeNode* a, TreeNode* b) { if (!a || !b) return false; if (dfs(a, b) || hasSubtree(a->left, b) || hasSubtree(a->right, b)) return true; } };
标签:right,return,dfs,子结构,TreeNode,left From: https://www.cnblogs.com/leetothemoon/p/16983904.html