码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Symmetric Tree

时间:2018-01-26 15:48:07      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:markdown   拒绝   binary   could   points   .com   while   int   来源   

Symmetric Tree 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/symmetric-tree/description/


Description

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Example

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.

Solution


class Solution {
private:
    bool validateSym(TreeNode* left, TreeNode* right) {
        if (left == NULL && right == NULL) {
            return true;
        } else if (left != NULL && right != NULL) {
            return (left -> val == right -> val &&
                    validateSym(left -> left, right -> right) &&
                    validateSym(left -> right, right -> left));
        }
        return false;
    }
public:
    bool isSymmetric(TreeNode* root) {
        if (root == NULL) return true;
        return validateSym(root -> left, root -> right);
    }
};

解题描述

这道题题意是判断给出的二叉树是不是一棵对称二叉树。上面给出的是递归的做法,还是不难想到的,不过迭代的做法就需要一些思路上的转换。不同于以往使用栈来模拟递归,这道题我使用的是队列来模拟节点递归检查的顺序:


class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (root == NULL) return true;
        queue<TreeNode*> lq, rq;
        lq.push(root -> left);
        rq.push(root -> right);
        while (!lq.empty() && !rq.empty()) {
            TreeNode *lnode = lq.front();
            lq.pop();
            TreeNode* rnode = rq.front();
            rq.pop();
            if (lnode == NULL && rnode == NULL) {
                continue;
            } else if (lnode != NULL && rnode != NULL) {
                if (lnode -> val != rnode -> val)
                    return false;
                lq.push(lnode -> left);
                lq.push(lnode -> right);
                rq.push(rnode -> right);
                rq.push(rnode -> left);
            } else {
                return false;
            }
        }
        if (!lq.empty() || !rq.empty())
            return false;
        else
            return true;
    }
};

[Leetcode] Symmetric Tree

标签:markdown   拒绝   binary   could   points   .com   while   int   来源   

原文地址:https://www.cnblogs.com/yanhewu/p/8359600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!