My solution to the LeetCode's Subtree of Another Tree passes all the test cases, but the code feels and looks ugly. Would appreciate an advice on how to improve it.
The problem:
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example:
Given tree s:
3 / \ 4 5 / \ 1 2
Given tree t:
4 / \ 1 2
Return true, because t has the same structure and node values with a subtree of s.
My solution:
class Solution { private: bool isSame(TreeNode* root_s, TreeNode* t) { if (!root_s && !t) return true; if (root_s && !t) return false; if (!root_s && t) return false; if (root_s->val != t->val) return false; return isSame(root_s->left, t->left) && isSame(root_s->right, t->right); } void preorder (TreeNode* s, TreeNode* t, bool& is_subtree) { if (!s) return; if (s->val == t->val) { if (isSame(t,s)) { is_subtree = true; return; } } preorder (s->left, t, is_subtree); preorder (s->right, t, is_subtree); } public: bool isSubtree(TreeNode* s, TreeNode* t) { bool is_subtree = false; preorder (s, t, is_subtree); return is_subtree; } };
For context, here's the definition of TreeNode
given by LeetCode:
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} };