Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3But the following [1,2,2,null,3,null,3] is not:
1 / \ 2 2 \ / 3 2Note: Bonus points if you could solve it both recursively and iteratively.(使用循环或递归是加分点)
思路:这道题其实可以使用中序遍历来进行判断,但由于c语言对于动态数组的处理较繁琐,不像C++有vector,java有list。下面给出一种递归求法,c++版的中序遍历方法可以见博客http://blog.csdn.net/jin_kwok/article/details/51162625
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool checkSon(struct TreeNode *leftSon, struct TreeNode *rightSon) { if(leftSon == NULL && rightSon == NULL) return 1; //没有孩子节点 else if(leftSon == NULL || rightSon == NULL) return 0; //只有左/右孩子 else if(leftSon->val == rightSon->val) //左右孩子存在且值相等 { return checkSon(leftSon->left, rightSon->right) && checkSon(leftSon->right, rightSon->left); } else return 0; //左右孩子存在且值不相等 } bool isSymmetric(struct TreeNode* root) { if(root == NULL) return 1; //空树 else return checkSon(root->left,root->right); }