LeetCode 打卡 SameTree

题目

Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

大意就是判断给定的两颗二叉树是不是相同的二叉树,就是判断每个节点上的值是否相同

分析

这道题可以使用递归的方法,先判断当前节点的值是否相同,如果相同,在判断左右节点的值是否相同

代码

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL && q != NULL || p != NULL && q==NULL) {
            return false;
        }
        if(p == NULL && q == NULL) {
            return true;
        }
        if (p -> val == q -> val) {
            if(isSameTree(p->left, q->right) && isSameTree(p->right, q->right)) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }
};
    原文作者:算法
    原文地址: https://www.twblogs.net/a/5bd3b05b2b717778ac20b320
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞