lintcode 1495. 叶子相似的树

请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个叶值序列 。
举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。
如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是叶相似的。
如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false

样例
样例 1:

输入: {1,#,2,3}, {1,2,#,3}
输出: true
解释: 
第一棵树:
   1
    \                
     2                
    /                 
   3   
第二棵树:
    1
   /
  2
 /
3
叶值序列都为:[3],所以相同
样例 2:

输入: {1,#,2,3}, {1,2,3}
输出: false
解释: 
第一棵树:
   1
    \                
     2                
    /                 
   3   
第二棵树:
   1
  / \                
 2   3    
第一棵树叶值序列都:[3],第二个树为:[2, 3],所以不相同
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root1: the first tree
     * @param root2: the second tree
     * @return: returns whether the leaf sequence is the same
     */
    bool leafSimilar(TreeNode * root1, TreeNode * root2) {
        // write your code here.
        recursion(root1,tmp1);
        recursion(root2,tmp2);
        if(tmp1.size()!=tmp2.size()) return false;
        for (int i = 0; i < tmp1.size(); i++) {
            /* code */
            if(tmp1[i]!=tmp2[i]) return false;
        }
        return true;
    }
    void recursion(TreeNode * root,vector<int> &tmp)
    {
        if(root->left==NULL&&root->right==NULL){tmp.push_back(root->val);return;}
        if(root->left)recursion(root->left,tmp);
        if(root->right)recursion(root->right,tmp);
    }
private:vector<int> tmp1;
        vector<int> tmp2;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值