Easy
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false
-
/**
-
* Definition for a binary tree node.
-
* struct TreeNode {
-
* int val;
-
* struct TreeNode *left;
-
* struct TreeNode *right;
-
* };
-
*/
-
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
-
if(p==NULL && q==NULL)
-
return 1;
-
if(p!=NULL && q!=NULL && p->val==q->val){
-
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
-
}
-
return 0;
- }
101. Symmetric Tree
Easy
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
-
/**
-
* Definition for a binary tree node.
-
* struct TreeNode {
-
* int val;
-
* struct TreeNode *left;
-
* struct TreeNode *right;
-
* };
-
*/
-
bool is_mirror(struct TreeNode *p, struct TreeNode* q){
-
if(p==NULL && q==NULL)
-
return 1;
-
if(p!=NULL && q!=NULL && p->val==q->val)
-
return is_mirror(p->left,q->right) && is_mirror(p->right,q->left);
-
return 0;
-
}
-
bool isSymmetric(struct TreeNode* root) {
-
if(root==NULL)
-
return 1;
-
return is_mirror(root->left,root->right);
- }