LeetCode解题报告 101. Symmetric Tree [easy]

来源:互联网 发布:ubuntu下配置snmp环境 编辑:程序博客网 时间:2024/06/04 08:19

题目描述

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

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

解题思路

题目很好理解,判断二叉树是否镜面对称。
用递归的方法来解,BFS。首先判断跟结点左右子树的情况,若同时为空则返回true,程序中止;若一个为空,返回false,程序中止;若同时为相同的顶点值,则继续判断两个结点各自的左右子树,若对称则1左等于2右且1右等于2左,不断递归下去。

复杂度分析

我们遍历整个输入树一次,因此时间复杂度是O(n),其中n是树中的节点总数。
递归调用的数量受到树的高度的约束。 在最坏的情况下,树是线性的,高度在O(n)。 因此,在最坏的情况下,由于对堆栈的递归调用而导致的空间复杂度为O(n)。

代码如下:
/** * 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;        return isSymmetric2(root->left, root->right);    }        bool isSymmetric2(TreeNode *l, TreeNode *r){        if (l==NULL&&r==NULL) {            return true;        }        if (l==NULL&&r!=NULL) {            return false;        }        if (l!=NULL&&r==NULL) {            return false;        }        if (l->val!=r->val) {            return false;        }        if (!isSymmetric2(l->left, r->right)) {            return false;        }        if (!isSymmetric2(l->right, r->left)) {            return false;        }        return true;            }};


0 0