【LeetCode-101】 Symmetric Tree(C++)

来源:互联网 发布:鬼吹灯 盗墓笔记 知乎 编辑:程序博客网 时间:2024/06/05 20:12

题目要求:判断一棵二叉树是不是轴对称。

解题方法:递归的方法(用循环实现现在不想写,有点困,等回头写了之后再来改博客)

/** * 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 isTwo(root->left,root->right);        if(root->left==NULL&&root->right==NULL)            return true;        return false;    }private:    bool isTwo(TreeNode* a,TreeNode* b){        if(a==NULL&&b==NULL)            return true;        if(a!=NULL&&b!=NULL){        if(a->val!=b->val)           return false;        else if(a->left==NULL&&a->right==NULL&&b->left==NULL&&b->right==NULL)          return true;        else{            if(isTwo(a->left,b->right)&&isTwo(a->right,b->left))               return true;        }        }        return false;    }};


0 0
原创粉丝点击