题解 | #对称的二叉树#

对称的二叉树

https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
#include <vector>
class Solution {
public:
    bool recursion(TreeNode* root1,TreeNode* root2)
    {
        if(root1 == nullptr && root2 == nullptr)return true;
        if(root1 == nullptr || root2 == nullptr || root1->val != root2->val) return false;
        return recursion(root1->left,root2->right) && recursion(root1->right,root2->left); 
    }

    void Inorder(TreeNode* tree,vector<int>& val)
    {
        if(tree == nullptr) return;
        Inorder(tree->left,val);
        val.push_back(tree->val);
        Inorder(tree->right,val);
    }
	
    bool isSymmetrical(TreeNode* pRoot) {
	  	//递归方法 如果对称那么一遍走左一边走右值应该是完全一样的。
        return recursion(pRoot,pRoot);
		//采用中序遍历结果对称来做,是错误的,没有办法去判断树型,除非你确定他是满二叉树 没意义
        // vector<int > val;
        // Inorder(pRoot,val);
        // int beg = 0;
        // int rbeg = val.size()-1;
        // while(beg < rbeg)
        // {
        //     if(val[beg++]!=val[rbeg--]) return false;
        // }
        // return true;
    }
};

全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 20:15
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务