首页 > 其他 > 详细

[LeetCode] Same Tree

时间:2017-07-16 22:13:13      阅读:279      评论:0      收藏:0      [点我收藏+]

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.

判断两棵树是否相同:1)如果两棵树的对应节点都为空,返回true。2)如果只有1课树的节点为空,返回false。3)如果两棵树的当前节点值相同,则递归判断下一个对应的节点。4)如果都不满足以上,则返回false。

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->val == q->val)
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        return false;
    }
};
// 0 ms

以上过程的简洁写法。

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr || q == nullptr)
            return p == q;
        return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};
// 3 ms

 

[LeetCode] Same Tree

原文:http://www.cnblogs.com/immjc/p/7192016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!