码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode|100|Same Tree

时间:2015-04-03 09:18:52      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:tree   binary   二叉树   

题目:Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
判断两棵二叉树是否相同。相同的二叉树有相同的结构和相同的值。
思路:
采用递归的方法。先判断根节点是否相同,然后再判断左右子树是否相同。
当两个根节点都为空指针时返回真。当两个根节点一个为空一个不为空时返回假。当两个根节点都不为空且两个根节点的值不相同时返回假。当两个根节点都不为空且两节点的值相同时递归判断左右子树是否为真。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        if(p==nullptr && q== nullptr)
            return true;
        if(p==nullptr && q!=nullptr)
            return false;
        if(p!=nullptr && q==nullptr)
            return false;
        if(p->val != q->val)
            return false;
        else
            return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);

    }
};

leetcode|100|Same Tree

标签:tree   binary   二叉树   

原文地址:http://blog.csdn.net/dainiwan/article/details/44850559

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!