LeetCode 100.Same Tree

本文解析了LeetCode上的100号问题“Same Tree”,介绍了如何通过递归比较两棵二叉树是否完全相同,并提供了C语言实现的示例代码。

LeetCode 100.Same Tree

Description:

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.

Example 1:

Input: 1 1
/ \ / \
2 3 2 3

   [1,2,3],   [1,2,3]

Output: true

Example 2:

Input: 1 1
/ \
2 2

   [1,2],     [1,null,2]

Output: false

Example 3:

Input: 1 1
/ \ / \
2 1 1 2

   [1,2,1],   [1,1,2]

Output: false


分析:

一道简单的题目,如果两棵树都为NULL,则返回true;否则从两棵树根部开始判断,若相等,则继续判断左子树,再判断右子树,利用递归即可解决。
这道题我是在做测试样例的时候懵了,因为好久没用过c语言指向结构体的指针,一直写不好main函数,所以又重新复习了一下指向结构体的指针,代码不常写真是不行。

代码如下:

#include <iostream>
using namespace std;
/**
 * Definition for a binary tree node.
 */
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) {
        // return (p != NULL && q != NULL && p->val == q->val 
        //  && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) 
        //  || (p == NULL && q == NULL);

        if (p == NULL && q == NULL) return true;
        else if (p != NULL && q != NULL && p-> val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) 
            return true;
        else return false;
    }
};
int main() {
    Solution s;

    int val1;
    cin >> val1;
    TreeNode tree1(val1);

    int left1;
    cin >> left1;
    TreeNode l1(left1);

    int right1;
    cin >> right1;
    TreeNode r1(right1);
    // 构造指向结构体的指针
    TreeNode* p;
    p = &tree1;
    p->left = &l1;
    p->right = &r1;

    int val2;
    cin >> val2;
    TreeNode tree2(val2);


    int left2;
    cin >> left2;
    TreeNode l2(left2);

    int right2;
    cin >> right2;
    TreeNode r2(right2);
    // 构造指向结构体的指针
    TreeNode* q;
    q = &tree2;
    q->left = &l2;
    q->right = &r2;
    cout << s.isSameTree(p, q) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值