leetcode-101. Symmetric Tree

来源:互联网 发布:卸载mac上的软件 编辑:程序博客网 时间:2024/05/25 21:35

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

For example, this binary tree is symmetric:
这里写图片描述

思路:递归,不递归的话用stack,但是逻辑会复杂

/** * 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 getSymmetric(root->left,root->right);    }    bool getSymmetric(TreeNode* left,TreeNode* right)    {        if(left == NULL || right == NULL)        {            return left == right;        }        if(left->val != right->val)        {            return false;        }        return getSymmetric(left->left,right->right) && getSymmetric(left->right,right->left);    }};
0 0
原创粉丝点击