题解 | #判断二叉树是否对称#

判断二叉树是否对称

http://www.nowcoder.com/practice/1b0b7f371eae4204bc4a7570c84c2de1

递归

class Solution {
public:
    //递归
    bool isSymmetric(TreeNode* root) {
        // write code here
        if(!root) return true;
        return isSymmetric_(root->left, root->right);
    }
    bool isSymmetric_(TreeNode* l, TreeNode* r){
        if(!l && !r) return true;
        if(!l || !r) return false;
        if(l->val != r->val)
            return false;
        return isSymmetric_(l->left, r->right) &&
            isSymmetric_(l->right, r->left);
    }
};

非递归

class Solution {
public:
    //非递归
    bool isSymmetric(TreeNode* root) {
        // write code here
        if (!root || !root->left && !root->right)
            return true;
        queue<TreeNode*> q;
        q.push(root->left);
        q.push(root->right);
        while (!q.empty()) {
            int sz = q.size();
            for (int i = 0; i < sz; i += 2) {
                TreeNode* L = q.front();
                q.pop();
                TreeNode* R = q.front();
                q.pop();
                if (!L && !R) continue;
                else if (!L || !R) return false;
                else if (L->val != R->val) return false;
                q.push(L->left);
                q.push(R->right);
                q.push(L->right);
                q.push(R->left);
            }
        }
        return true;
    }
};
全部评论

相关推荐

LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司7个岗位
点赞 评论 收藏
分享
05-30 18:54
武汉商学院 Java
湫湫湫不会java:先投着吧,大概率找不到实习,没实习的时候再加个项目,然后把个人评价和荣誉奖项删了,赶紧成为八股战神吧,没实习没学历,秋招机会估计不多,把握机会。或者说秋招时间去冲实习,春招冲offer,但是压力会比较大
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务