Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8)
.
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true
if and only if the two given trees with head nodes root1
and root2
are leaf-similar.
Constraints:
- Both of the given trees will have between
1
and200
nodes. - Both of the given trees will have values between
0
and200
A:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector<int> A,B; getLeaf(root1, A); getLeaf(root2, B); if(A.size() != B.size() ) return false; for(int i =0;i<A.size(); ++i) if(A[i] != B[i]) return false; return true; } private: void getLeaf(const TreeNode *root, vector<int> &V){ if(!root) return; if(! root->left && ! root->right) V.push_back(root->val); if(root->left) getLeaf(root->left, V); if(root->right) getLeaf(root->right, V); } };
No comments:
Post a Comment