其他分享
首页 > 其他分享> > symmetric-tree

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.
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

【解题思路】使用递归法

【考查内容】树,递归

/**
 * 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;
        return isSymmetric(root->left,root->right);
    }
    bool isSymmetric(TreeNode *l,TreeNode *r){
    	if(l==NULL && r==NULL)
    		return true;
    	if(l==NULL || r==NULL)
    		return false;
    	if(l->val==r->val)
    		return isSymmetric(l->left,r->right) && isSymmetric(l->right,r->left);
    	return false;
    }
};

标签:right,TreeNode,tree,symmetric,return,isSymmetric,NULL
来源: https://blog.csdn.net/weixin_36909758/article/details/90668684