LeetCode 100.Same Tree

来源:互联网 发布:互联网数据分析师职责 编辑:程序博客网 时间:2024/06/04 20:10

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;}
原创粉丝点击