-
[LeetCode] 872. Leaf-Similar Trees c++Coding Test/LeetCode 2022. 12. 22. 15:33728x90
- 문제
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'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 977. Squares of a Sorted Array c++ (0) 2022.12.23 [LeetCode] 145. Binary Tree Postorder Traversal c++ (0) 2022.12.22 [LeetCode] 965. Univalued Binary Tree c++ (0) 2022.12.22 [LeetCode] 463. Island Perimeter c++ (0) 2022.12.22 [LeetCode] 559. Maximum Depth of N-ary Tree c++ (0) 2022.12.20