[Leetcode] Symmetric Tree

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Symmetric Tree相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode - Symmetric Tree

LeetCode(101):Symmetric Tree

[LeetCode]题解(python):101 Symmetric tree

LeetCode OJ 101Symmetric Tree

LeetCode OJ 101Symmetric Tree

[LeetCode]题解(python):101-Symmetric Tree