LeetCode简单题:100. 相同的树(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/same-tree/
要点:递归,树
Python,C++,Java都用了相同的递归方法
如果当前比较的两个节点都是空的,返回true
如果当前比较的两个节点只有一个是空的,直接返回false
如果当前比较的两个节点都非空,如果它们值不一样返回false
如果以上都不满足,返回isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)

二.Python实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p==None and q==None:
            return True
       
        if p == None and q != None:
            return False
        
        if p!= None and q== None:
            return False

        if p.val!=q.val:
            return False

        return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

三.C++实现

/**
 * 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==NULL && q==NULL){
        return true;
    }
    if(p!=NULL && q!=NULL && p->val==q->val  ){
        return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    }else {
        return false;
    }
}
};

四.java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null&&q==null) return true;
        else if((p==null&&q!=null)||(p!=null&&q==null)) return false;
        else if(p.val!=q.val) return false;
        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);

    }
}

你可能感兴趣的:(LeetCode简单题:100. 相同的树(Python,C++,Java))