[LeetCode] Symmetric Tree

来源:互联网 发布:linux 设置语言为英文 编辑:程序博客网 时间:2024/06/10 04:20

前言

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

题目

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;    }};
0 0
原创粉丝点击