872. Leaf-Similar Trees

1,题目要求
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
872. Leaf-Similar Trees_第1张图片
判断两棵树的叶子节点序列是否相同。

2,题目思路
并不是很难,只不过利用dfs的方法对树进行遍历,并利用vector对叶子节点进行记录,最后再比较两个得到的vector是否相同就可以得到结果了。

3,程序源码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */     
class Solution {
public:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> ro1, ro2;
        dfs(root1, ro1);
        dfs(root2, ro2);

        return ro1 == ro2;
    }

private:
    void dfs(TreeNode* root, vector<int>& v)
    {
        if(root == nullptr)    return;
        if(root->left == nullptr && root->right == nullptr)
            v.push_back(root->val);    
        dfs(root->left, v);
        dfs(root->right, v);
    }
};

你可能感兴趣的:(C++OJ,LeetCode,Self-Culture)