LeetCode 872. Leaf-Similar Trees

这里写图片描述

解析

先序遍历,遇到叶子节点就push进vector

class Solution {
public:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> leaf1,leaf2;
        travel(root1,leaf1);
        travel(root2,leaf2);
        return leaf1==leaf2;
    }
    void travel(TreeNode* root,vector<int> &data){
        if(root ==NULL)
            return;
        else if(root->left ==NULL && root->right == NULL)
            data.push_back(root->val);
        travel(root->left,data);
        travel(root->right,data);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/81835812
今日推荐