Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1559126
  • 博文数量: 327
  • 博客积分: 10000
  • 博客等级: 上将
  • 技术积分: 3556
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-05 21:28
个人简介

东黑布衣,流浪幽燕。 真诚善良,值得信赖。

文章分类

全部博文(327)

我的朋友

分类: BSD

2018-12-31 22:47:38

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. }







阅读(2191) | 评论(0) | 转发(0) |
0

上一篇:自我介绍

下一篇:LeetCode 0094 0144

给主人留下些什么吧!~~