首页 > 代码库 > [LeetCode]Symmetric Tree

[LeetCode]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:

    1
   /   2   2
 / \ / 3  4 4  3

But the following is not:

    1
   /   2   2
   \      3    3

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


【分析】

【代码】

/*********************************
*   日期:2014-12-24
*   作者:SJF0115
*   题目: Symmetric Tree
*   来源:https://oj.leetcode.com/problems/symmetric-tree/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
using namespace std;

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;
        }//if
        return isSymmetric(root->left,root->right);
    }
private:
    bool isSymmetric(TreeNode *l,TreeNode *r) {
        // 两个节点都为空
        if(l == NULL && r == NULL){
            return true;
        }//if
        // 两个节点一个为空一个不为空
        if(l == NULL || r == NULL){
            return false;
        }//if
        // 两个节点val相同
        // 判断l的左子结点和r的右子节点
        // 判断l的右子结点和r的左子节点
        if(l->val == r->val){
            bool leftVal = isSymmetric(l->left,r->right);
            bool rightVal = isSymmetric(l->right,r->left);
            return leftVal && rightVal;
        }//if
        return false;
    }
};

//按先序序列创建二叉树
int CreateBTree(TreeNode*& T){
    int data;
    //按先序次序输入二叉树中结点的值,-1表示空树
    cin>>data;
    if(data =http://www.mamicode.com/= -1){>

【复杂度】

时间复杂度 O(n),空间复杂度 O(logn)


技术分享



[LeetCode]Symmetric Tree