Same Tree - 判断两棵二叉树是否相同

这个题相对来说是比较简单的,思路为:利用先序遍历来每个点进行判断

struct TreeNode {
    int value;
    TreeNode *leftTreeNode;
    TreeNode *rightTreeNode;
};

bool isSameTree(TreeNode *firstTreeNode, TreeNode *secondTreeNode) {
    if (firstTreeNode == NULL && secondTreeNode == NULL) { // 两个点都为空
        return true;
    } else if (firstTreeNode == NULL || secondTreeNode == NULL) { // 其中一个点为空
        return false;
    } else { // 两个点都不为空
        if (firstTreeNode->value == secondTreeNode->value) {
            return isSameTree(firstTreeNode->leftTreeNode, secondTreeNode->leftTreeNode) && isSameTree(firstTreeNode->rightTreeNode, secondTreeNode->rightTreeNode);
        } else {
            return false;
        }
    }
}
    原文作者:郑明明
    原文地址: https://www.jianshu.com/p/6f35d6a07fd3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞