Symmetric Tree
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.
解题思路:
题目要求分别用递归法和迭代法做。
1、递归法。思路挺简单,每次检查一对节点,验证这对节点的值是否相同,并且节点1的左孩子与节点2的右孩子的对称的,并且节点1的右孩子与节点2的左孩子是对称的。否则,返回false。
/** * 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) { return isSysmetricHelp(root, root); } bool isSysmetricHelp(TreeNode* root1, TreeNode* root2){ if(root1==NULL && root2==NULL){ return true; } if(root1==NULL || root2==NULL){ return false; } if(root1->val != root2->val){ return false; } return isSysmetricHelp(root1->left, root2->right)&&isSysmetricHelp(root1->right, root2->left); } };2、迭代法。有句话,递归转化成非递归,无非就是用栈或堆来存储中间状态。我们用两个队列来存储待比较的两个节点即可。
/** * 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; } //两个队列的大小逻辑上一定相同 queue<TreeNode*> left({root}); queue<TreeNode*> right({root}); while(!left.empty()){ TreeNode* leftNode = left.front(); TreeNode* rightNode = right.front(); left.pop(); right.pop(); if(leftNode->val!=rightNode->val){ return false; } if(leftNode->left!=NULL&&rightNode->right!=NULL){ left.push(leftNode->left); right.push(rightNode->right); }else if(leftNode->left!=NULL || rightNode->right!=NULL){ return false; } if(leftNode->right!=NULL&&rightNode->left!=NULL){ left.push(rightNode->left); right.push(leftNode->right); }else if(leftNode->right!=NULL || rightNode->left!=NULL){ return false; } } return true; } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45789951