码疯窝

LeetCode 每日一题 — Same Tree

2014/12/15 11:51:46    分类: 日志连载    0人评论 次浏览

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.

算法分析: 这题目就是判断node是否是一样. 比较val 就行了.

Java:

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

C++:

/**
 * Definition for binary tree
 * 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) {
        return (p == NULL && q == NULL) ? true :
                    (p == NULL || q == NULL) ? false :
                    (p->val == q->val) ? isSameTree(p->left, q->left) && isSameTree(p->right, q->right) : false;
    }
};

Python:

# 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 (p == None and q == None):
            return True
        if (p == None or q == None):
            return False
        if (p.val == q.val):
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        return False
       
继续查看有关 日志连载的文章

0个访客评论