【LeetCode笔记】判断一棵树是否为镜像

最初思路:

1.求树的中序遍历,存入vector;

2.判断vector是否为为镜像;

/**
 * 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:
    vector<int> v;

    void get(int a){
        v.push_back(a);
    }
    
    void LDR(TreeNode *root){
        if (root==NULL)
            return;
        else{
            LDR(root->left);
            get(root->val);
            LDR(root->right);
        }
        return;
    }
    
    bool reverse(vector<int> n,int start,int end,int length){
        if (length==0||length==1)
            return true;
        if (n.at(start)!=n.at(end))
            return false;
        else{
            return reverse(n,start+1,end-1,length-2);
        }
    }
    bool isSymmetric(TreeNode* root) {
        LDR(root);
        return reverse(v,0,v.size()-1,v.size());
    }
};
错误原因:

中序遍历并不能唯一确定一棵树啊。。。



正解:

1.判断结构是否对称  要么没有左右子树,要么有左子树就要有右子树

2.判断值是否对称:除根节点外,左子树的左边和右子树的右边值要相同

扫描二维码关注公众号,回复: 5871347 查看本文章

class Solution {
public:
    bool compare(TreeNode* root1,TreeNode* root2){
        if(root1==NULL&&root2==NULL)
            return true;
        else if((root1==NULL&&root2!=NULL)||(root1!=NULL&&root2==NULL))
            return false;
        else{
            if(root1->val!=root2->val)
                return false;
            else
                return compare(root1->left,root2->right)&&compare(root1->right,root2->left);
        }
    }
    bool isSymmetric(TreeNode* root) {
        if (root==NULL)
            return true;
        if (root->left==NULL&&root->right==NULL)
            return true;
        if((root->left==NULL&&root->right!=NULL)||(root->left!=NULL&&root->right==NULL))
            return false;
        return compare(root->left,root->right);
    }
};



猜你喜欢

转载自blog.csdn.net/macidoo/article/details/69668985
今日推荐