100. 相同的树
Java
/*
* @Author: Goog Tech
* @Date: 2020-07-24 19:08:50
* @Description: https://leetcode-cn.com/problems/same-tree/
* @FilePath: \leetcode-googtech\#100. Same Tree\Solution.java
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 递归法
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null) {
return true;
}
else if(p!=null && q!=null && p.val == q.val) {
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}else {
return false;
}
}
}
Python
'''
@Author: Goog Tech
@Date: 2020-07-24 19:08:58
@Description: https://leetcode-cn.com/problems/same-tree/
@FilePath: \leetcode-googtech\#100. Same Tree\Solution.py
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
# 递归法
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not p and not q:
return True
elif p is not None and q is not None and p.val==q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
else:
return False