Coding Test/LeetCode
[LeetCode] 872. Leaf-Similar Trees c++
owls
2022. 12. 22. 15:33
728x90
- 문제
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.
Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true
두개의 tree가 주어지고 가장 마지막 depth 노드들의 sequence를 구하는 문제이다.
- 문제 해결
class Solution {
private:
void dfs(TreeNode* curr, vector<int>& vec){
if(!curr){
return;
}
if( !(curr->left || curr->right)){
vec.push_back(curr->val);
}
dfs(curr->left, vec);
dfs(curr->right, vec);
}
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> v1;
vector<int> v2;
dfs(root1, v1);
dfs(root2, v2);
if(v1 == v2)
return true;
return false;
}
};
728x90