您的位置:首页 > 其它

leetcode刷题。总结,记录,备忘 100

2015-05-23 22:13 281 查看
leetcode 100题是判断2个二叉树是否相同

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.

这个题目同样使用深度优先搜索,利用递归,首先判断当前节点值是否相同,再判断每个当前节点的左右子树是否相同,如果3个条件都相同才返回真。递归结束条件是2棵树都遍历到了最远的叶节点,返回真,或者其中一个已到最远叶节点,另一个并没有,就返回假。

bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if (p == NULL && q == NULL)
    return true;
    else if (p == NULL || q == NULL)
    return false;
    
    bool flagV;
    if (p->val == q->val)
    flagV = true;
    else
    flagV = false;
    
    bool flagL = isSameTree(p->left, q->left);
    bool flagR = isSameTree(p->right, q->right);
    
    if (flagL && flagR && flagV)
    return true;
    else
    return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: