欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode 100. Same Tree相同的树 (C++)

程序员文章站 2022-03-25 16:15:32
题目: 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 i ......

题目:

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

分析:

给定两个二叉树,判断他们是否相同,相同的二叉树拥有相同的结构,且节点的值也要相等。

递归求解。对于两个节点是否相同,有如下情况,当两个节点的左右节点均为空时返回true,如果两个节点,有一非空时,返回false,如果两个节点值不同时,返回false,之后递归求解节点的左右节点。

程序:

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