[LeetCode] Symmetric Tree

前言

一道树相关的简单题,判断二叉树是否对称。

题目

https://leetcode.com/problems/symmetric-tree/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

分析

这类题一般都有递归和非递归两种基本思路。对于此题而言,递归方式相对easy to understand, 而非递归解法需要队列来操作。具体思路可见代码,所有思路的关键就是“镜面对称”。

代码

Recursive solution:

class Solution {
public:
  bool isSymmetric(TreeNode* root) {
    if (root == NULL) // The tree is empty
      return 1;
    return IsMirror(root->left, root->right); // A helper to judge whether two subtree is mirror   
  }
  bool IsMirror(TreeNode *p, TreeNode *q) {
    if (p == NULL && q == NULL) return 1; // p and q are both empty tree
    else if (p == NULL || q == NULL) return 0; // p (or q) is empty
    return (p->val == q->val) && IsMirror(p->left, q->right) && IsMirror(p->right, q->left);
  }
};

Non-recursive solution:

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        TreeNode *left, *right;
        if (root == NULL)
            return true;

        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);

        while (!q1.empty() && !q2.empty()){
            left = q1.front();
            q1.pop();
            right = q2.front();
            q2.pop();
            if (NULL == left && NULL == right)
                continue;
            if (NULL == left || NULL == right)
                return false;
            if (left->val != right->val)
                return false;
            q1.push(left->left);
            q1.push(left->right);
            q2.push(right->right);
            q2.push(right->left);
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值