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
思路:递归。
struct TreeNode{ int data; TreeNode *left; TreeNode *right; TreeNode(int x):data(x),left(NULL),right(NULL) {} }; bool isMiror(TreeNode *n1,TreeNode *n2) { if(n1 == NULL && n2 == NULL) return true; if(n1 == NULL || n2 == NULL || n1->data != n2->data) return false; return isMiror(n1->left,n2->right) && isMiror(n1->right,n2->left); } bool isSymmetric(TreeNode *root) { if(root==NULL || (root->left == NULL && root->right == NULL)) return true; return isMiror(root->left,root->right); }
本文介绍了一种通过递归方法判断二叉树是否关于其中心对称的有效算法。通过对左右子树进行镜像比较,可以高效地确定二叉树的对称性。
377

被折叠的 条评论
为什么被折叠?



