【leetcode】【easy】100. Same Tree

100. Same Tree

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

题目链接:https://leetcode-cn.com/problems/same-tree/

思路

递归编程练习,非递归就不写了。

法一:递归

判断当前节点是否相等,再一起向下遍历。

/**
 * 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) {
        if((q && !p) || (!q && p)) return false;
        if(!q && !p) return true;
        if(q->val != p->val) return false;
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};

法二:遍历输出

分别输出成序列,对比序列。

发布了127 篇原创文章 · 获赞 2 · 访问量 3751

猜你喜欢

转载自blog.csdn.net/lemonade13/article/details/104376966