文章目录
  1. 1. Same Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Same Tree

题目

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

思路

逐个比较就行

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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 && !q)
return true;
if(!p && q)
return false;
if(p && !q)
return false;
if(p && q && p->val==q->val)
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
else
return false;
}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if not p and not q:
return True
if not p and q:
return False
if p and not q:
return False
if p and q and p.val!=q.val:
return False
return self.isSameTree(p.right,q.right) and self.isSameTree(p.left,q.left)
文章目录
  1. 1. Same Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题