c/c++语言开发共享LeetCode 100. Same Tree相同的树 (C++)

题目: 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);      }  };

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/603474.html

(0)
上一篇 2021年5月11日
下一篇 2021年5月11日

精彩推荐