当前位置: 移动技术网 > IT编程>开发语言>C/C++ > LeetCode 100. Same Tree相同的树 (C++)

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

2019年05月12日  | 移动技术网IT编程  | 我要评论

乾坤兽王,理财通收益,异世之只手遮天

题目:

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);
    }
};

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网