标签:des style blog io color ar for sp div
开始做算法题了,从AC率最高的开始做,思路一开始就找到了要用递归,但是细节上有很多需要修炼的,基础还是要打牢固。要判断是否镜像对称,只需要每次判断根节点的左子节点的左、右儿子是否相对应的等于右子节点的右、左儿子,然后递归调用isNodeSymmetric()即可。附上解法:
/** * Definition for binary tree * 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; else if(root->left==NULL&&root->right==NULL)return true; else return isNodeSymmetric(root->left,root->right); } bool isNodeSymmetric(TreeNode *left,TreeNode *right) { if(left==NULL&&right==NULL)return true; if((left == NULL && right != NULL) || (left != NULL && right == NULL) ) return false; else if(left->val!=right->val)return false; else return isNodeSymmetric(left->left,right->right)&& isNodeSymmetric(left->right,right->left); } };
标签:des style blog io color ar for sp div
原文地址:http://www.cnblogs.com/sofeii/p/4055701.html