[leetcode]Leaf-Similar Trees

jun·2021년 4월 9일
0
post-thumbnail

유의할점

풀이

코드

C++ : 내가 짠 코드

/**
 * 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:
    void leaf(TreeNode* root,vector<int>&res){
        if(root==NULL)
            return;
        if(root->left==NULL&&root->right==NULL){
            res.push_back(root->val);
            return;
        }
        
        leaf(root->left,res);
        leaf(root->right,res);
    }
    
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> left;
        vector<int> right;
        leaf(root1,left);
        leaf(root2,right);
        
        if(left.size()!=right.size())
            return false;
        return equal(left.begin(),left.end(),right.begin());
    }
};

C++ : String

bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        string t1, t2;
        DFS(root1, t1);
        DFS(root2, t2);
        return t1==t2;
    }
    
void DFS(TreeNode* root, string& s) {
	if(root==NULL) return;
  if(root->left==NULL&&root->right==NULL) s+=to_string(root->val)+"#";
  DFS(root->left, s);
  DFS(root->right, s);
}
profile
Computer Science / Algorithm / Project / TIL

0개의 댓글