LeetCode 101: Symmetric Tree

Symmetric Tree

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

For example, this binary tree is symmetric:
Symmetric Tree
But the following is not:
Not Symmetric Tree

Note:
Bonus points if you could solve it both recursively and iteratively.

解题思路

思路一:只需要判断左子树和右子树是否对称即可,因此可以将原问题归结为判断两棵二叉树是否互为镜像。

首先比较两个根结点 r1 r2 的值是否相等,然后递归判断 r1 的左子树和 r2 的右子树是否互为镜像以及 r1 的右子树和 r2 的左子树是否互为镜像。

代码如下:

/**
 * 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 {
    bool isMirror(TreeNode *tree1, TreeNode *tree2) {
        if (tree1 == NULL && tree2 == NULL) return true;
        if (tree1 == NULL || tree2 == NULL) return false;

        if (tree1->val != tree2->val) return false;

        return isMirror(tree1->left, tree2->right) && isMirror(tree1->right, tree2->left);
    }
public:
    bool isSymmetric(TreeNode* root) {
        if (root == NULL) return true;

        return isMirror(root->left, root->right);
    }
};

思路二:可以将上述递归算法改写成迭代算法,代码如下:

/**
 * 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;

        stack<TreeNode *> nodeStack;
        nodeStack.push(root->left);
        nodeStack.push(root->right);
        while (!nodeStack.empty()) {
            TreeNode *tree1 = nodeStack.top();
            nodeStack.pop();
            TreeNode *tree2 = nodeStack.top();
            nodeStack.pop();

            if (tree1 == NULL && tree2 == NULL) continue;
            if (tree1 == NULL || tree2 == NULL) return false;

            if (tree1->val != tree2->val) return false;

            nodeStack.push(tree1->left);
            nodeStack.push(tree2->right);
            nodeStack.push(tree1->right);
            nodeStack.push(tree2->left);
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值