Leetcode:Same Tree

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.

Answer 

只要判斷兩邊的 Binary Tree 是否相同即可,沒有任何難度,要說最難的話是在於如何讓他用最快的方式得到答案。

Javascript

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree(p, q){
    var x, y;
    if(p||q){
        if((p != null) && (q != null)){
            if(p.val == q.val){
                x = isSameTree(p.left, q.left);
                y = isSameTree(p.right, q.right);
            }else{
                return false;
            }
        }else{
            return false;
        }
    }else{
        return true;
    }
    if(x&&y){
        return true;
    }else{
        return false;
    }
}
//Min:108ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

C

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    bool x, y;
    if((p!=NULL)&&(q!=NULL)){
        if(p->val == q->val){
            x = isSameTree(p->left, q->left);
            y = isSameTree(p->right, q->right);
        }else{
            return false;
        }
    }else if((q==NULL)&&(p==NULL)){
        return true;
    }else{
        return false;
    }
    if(x&&y){
        return true;
    }else{
        return false;
    }
}
//Min:0ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

Python

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

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if (p != None) and (q != None):
            if(p.val == q.val):
                x = self.isSameTree(p.left, q.left)
                y = self.isSameTree(p.right, q.right)
            else:
                return False
        elif (p == None) and (q == None):
            return True
        else:
            return False
            
        if x and y:
            return True
        else:
            return False
#Min:40ms

我看到有人用單行解決了這個問題,但是單行好長阿!

留言

這個網誌中的熱門文章

Leetcode:Number of 1 Bits