题解 | #判断二叉树是否对称#
判断二叉树是否对称
http://www.nowcoder.com/practice/1b0b7f371eae4204bc4a7570c84c2de1
- 使用两个根节点的方式来迭代这棵树。
- 其他情况看注释。
- 注意最有对应的节点,除了同时看对应的左边和右边的节点,也要看对应的右边和左边的节点。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return bool布尔型
*/
bool isS(TreeNode* Lroot,TreeNode* Rroot){
//base case
if(!Lroot&&!Rroot) return true;//left、right指针指向的节点必须同时为空,返回true
if(!Lroot || !Rroot) return false;//left、right指针指向的节点不同时为空,返回false
if(Lroot->val!=Rroot->val) return false;//left、right指针指向的节点都不为空,值不相同,返回false;
return isS(Lroot->left,Rroot->right)&& isS(Lroot->right,Rroot->left);
}
bool isSymmetric(TreeNode* root) {
// write code here
if(!root) return true;
return isS(root,root);
}
};算法解析 文章被收录于专栏
这里主要是算法岗的自我思路总结

查看9道真题和解析