Maximum Depth of Binary Tree (C++)
Pow(x, n) (C++)

Same Tree (C++, Python)

kitt posted @ 2013年9月24日 01:03 in LeetCode , 1905 阅读

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.

 

/**
 * 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) {
        if ((p == NULL) && (q == NULL)) return true;  //两个node都是空的
        if ( (!p && q) || (p && !q) ) return false;   //两个node有一个是空的
        if (p->val != q->val) return false;           //两个node都不空
        if (isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
            return true;
        else
            return false;
    }
};
# Accepted on 03/24/2014, runtime: 120 ms
#
# 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 == q == None:
            return True
        if not (p and q) or p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter