标签:程序员面试题精选100题 遍历 二叉树
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
Note:
Bonus points if you could solve it both recursively and iteratively.
无
/********************************* * 日期:2014-12-24 * 作者:SJF0115 * 题目: Symmetric Tree * 来源:https://oj.leetcode.com/problems/symmetric-tree/ * 结果:AC * 来源:LeetCode * 总结: **********************************/ #include <iostream> using namespace std; 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 return isSymmetric(root->left,root->right); } private: bool isSymmetric(TreeNode *l,TreeNode *r) { // 两个节点都为空 if(l == NULL && r == NULL){ return true; }//if // 两个节点一个为空一个不为空 if(l == NULL || r == NULL){ return false; }//if // 两个节点val相同 // 判断l的左子结点和r的右子节点 // 判断l的右子结点和r的左子节点 if(l->val == r->val){ bool leftVal = isSymmetric(l->left,r->right); bool rightVal = isSymmetric(l->right,r->left); return leftVal && rightVal; }//if return false; } }; //按先序序列创建二叉树 int CreateBTree(TreeNode*& T){ int data; //按先序次序输入二叉树中结点的值,-1表示空树 cin>>data; if(data == -1){ T = NULL; } else{ T = new TreeNode(data); //构造左子树 CreateBTree(T->left); //构造右子树 CreateBTree(T->right); } return 0; } int main() { Solution solution; TreeNode* root(0); CreateBTree(root); cout<<solution.isSymmetric(root); }
时间复杂度 O(n),空间复杂度 O(logn)
标签:程序员面试题精选100题 遍历 二叉树
原文地址:http://blog.csdn.net/sunnyyoona/article/details/42119945