題目說明:給定兩棵樹,要判斷兩棵樹是否相等
Case 1
Input: p = [1,2,3], q = [1,2,3]
Output: true
Case 2
Input: p = [1,2], q = [1,null,2]
Output: false
Case 3
Input: p = [1,2,1], q = [1,1,2]
Output: false
要判斷兩棵樹是否相同,我們需要考慮兩個情況:
附上程式碼以及註解
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;//兩棵樹都為空值(null)就回傳true
if (q == null || p == null) return false;//其中之一為空值(null)回傳false
if (p.val != q.val) return false;//若兩者的值不相同就回傳false
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
//用遞迴的方式重複檢查兩棵樹的左右子樹是否相同
}
}
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True #兩棵樹都為空值(None)就回傳true
if not q or not p:
return False #其中之一為空值(None)回傳false
if p.val != q.val:
return False #若兩者的值不相同就回傳false
return self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left)
#用遞迴的方式重複檢查兩棵樹的左右子樹是否相同