递归法
执行用时 :12 ms, 在所有 C++ 提交中击败了43.44%的用户
内存消耗 :14.6 MB, 在所有 C++ 提交中击败了95.56%的用户
/** * 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; if( isMirror(root->left, root->right)) return true; else return false; } bool isMirror(TreeNode* lc, TreeNode* rc) { if(lc == NULL && rc == NULL) return true; if(lc == NULL || rc == NULL) return false; else { if (lc->val == rc->val) return (isMirror(lc->left, rc->right) && isMirror(lc->right, rc->left)); else return false; } } };
时间复杂度:
O(n),因为算法过程要遍历树的每一个节点,节点数量为n。
空间复杂度:
O(n),递归函数使用的栈空间与树的层数有关。如果树为线性结构,其层数为n,所以空间复杂度为O(n)