思路

可以参考官方题解,我这里只说一下自己的错误。我刚开始想的对称树利用中序遍历出来的序列也是对称的,其实是不对的。比如:1 2 3 3 # 2 #。这个序列中序就是3 2 1 2 3 。但其不是对称二叉树。

错误代码

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
	vector<int> v;
	void InOrder(TreeNode* pRoot){
		if(pRoot)
		{
			InOrder(pRoot->left);
			v.push_back(pRoot->val);
			InOrder(pRoot->right);
		}
	}
    bool isSymmetrical(TreeNode* pRoot) {
    	
    	if(pRoot==nullptr) return true;
		InOrder(pRoot);
		for(int i = 0; i<v.size();i++)
		{
			if(v.at(i)!=v.at(v.size()-i-1)) return false;
		}
		return true;
    }

};

正确解答(参考官方)

class Solution {
public:
    bool isSame(TreeNode *root1, TreeNode *root2) {
        if (!root1 && !root2) return true;
        if (!root1 || !root2) return false;
        return root1->val == root2->val && 
        isSame(root1->left, root2->right) &&
        isSame(root1->right, root2->left);
    }
    bool isSymmetrical(TreeNode* pRoot)
    {
        return isSame(pRoot, pRoot);
    }

};