100. Same Tree
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

  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  * int val;
  5.  * struct TreeNode *left;
  6.  * struct TreeNode *right;
  7.  * };
  8.  */
  9. bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
  10.     if(p==NULL && q==NULL)
  11.         return 1;
  12.     if(p!=NULL && q!=NULL && p->val==q->val){
  13.         return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
  14.     }
  15.     return 0;
  16. }






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.



  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  * int val;
  5.  * struct TreeNode *left;
  6.  * struct TreeNode *right;
  7.  * };
  8.  */
  9. bool is_mirror(struct TreeNode *p, struct TreeNode* q){
  10.     if(p==NULL && q==NULL)
  11.         return 1;
  12.     if(p!=NULL && q!=NULL && p->val==q->val)
  13.         return is_mirror(p->left,q->right) && is_mirror(p->right,q->left);
  14.     return 0;
  15. }
  16. bool isSymmetric(struct TreeNode* root) {
  17.     if(root==NULL)
  18.         return 1;
  19.     return is_mirror(root->left,root->right);
  20. }







10-23 22:32