102.(101)对称二叉树(递归法)

    技术2022-07-12  85

    题目描述:

    给定一个二叉树,检查它是否是镜像对称的。

    例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

        1    / \   2   2  / \ / \ 3  4 4  3

    但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

        1    / \   2   2    \   \    3    3

    代码:

     

    /** * 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 symMirror(root->left,root->right); } bool symMirror(TreeNode* root_l,TreeNode* root_r) { if(root_l==NULL&&root_r==NULL) return true; if(root_l==NULL||root_r==NULL) return false; if(root_l->val==root_r->val) return symMirror(root_l->left,root_r->right)&&symMirror(root_l->right,root_r->left); return false; } };

    执行效率:

    执行用时:4 ms, 在所有 C++ 提交中击败了87.45%的用户

    内存消耗:12.5 MB, 在所有 C++ 提交中击败了100.00%的用户

    Processed: 0.020, SQL: 9