算法作业HW17:LeetCode101 Symmetric Tree

Description:

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:

 

 

Note:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3
Bonus points if you could solve it both recursively and iteratively


Solution:

  Analysis and Thinking:

给定要求在一棵二叉树作为输入的情况下,检查它是否是它自身的轴对称的镜像。这题比较简单,只需要看图做题,利用递归的方法就可以解决,一开始递归左右子树,当满足以下条件:第一棵树的右子树与第二棵树的左子树相同且第二棵树的右子树与第一棵树的左子树也完全相同时,我们就说该树满足对称条件,是轴对称的镜像


 Steps:

1.判断根节点是否为空,若为空,返回true

2.如果左右节点都不为空,进入递归,递归过程中,当出现任意一次当前两节点值不相等,则返回false

3.直到递归至叶子节点,则其左右子树为空,递归返回true,为正确结果

Codes:

/** 
 * Definition for a binary tree node. 
 * struct TreeNode { 
 *     int val; 
 *     TreeNode *left; 
 *     TreeNode *right; 
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
 * }; 
 */  
class Solution {  
public:  
    bool isSymmetric(TreeNode* root) {  
        if(root==NULL)  
            return true;  
        if(root->left!=NULL&&root->right!=NULL)  
            return isMinor(root->left,root->right);  
        if(root->left==NULL&&root->right==NULL)  
            return true;  
        return false;  
    }  
private:  
    bool isMinor(TreeNode* x,TreeNode* y){  
        if(x==NULL&&y==NULL)  
            return true;  
        if(x!=NULL&&y!=NULL){  
        if(x->val!=y->val)  
           return false;  
        else if(x->left==NULL&&x->right==NULL&&y->left==NULL&&y->right==NULL)  
          return true;  
        else{  
            if(isMinor(x->left,y->right)&&isMinor(x->right,y->left))  
               return true;  
        }  
        }  
        return false;  
    }  
};  






 

Results:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值