Skip to content
Browse files

sametree

  • Loading branch information...
1 parent 365e204 commit d174d54abe9dded6a55f8bac7e2ab43eedff6219 = committed
Showing with 41 additions and 0 deletions.
  1. +41 −0 same-tree.cpp
View
41 same-tree.cpp
@@ -0,0 +1,41 @@
+
+// http://oj.leetcode.com/problems/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.
+
+
+
+/**
+ * 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==q) {
+ return true;
+ }
+
+ if(p!=NULL and q==NULL) {
+ return false;
+ }
+ if(p==NULL and q!=NULL) {
+ return false;
+ }
+
+ if(p->val != q->val) {
+ return false;
+ }
+
+ bool isSameLeft = isSameTree(p->left, q->left);
+ bool isSameRight = isSameTree(p->right, q->right);
+ return (isSameLeft==true and isSameRight==true) ? true : false;
+ }
+};

0 comments on commit d174d54

Please sign in to comment.
Something went wrong with that request. Please try again.