对称的二叉树

来源:互联网 发布:数据库概论第5版答案 编辑:程序博客网 时间:2024/06/06 10:01

题目:

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

分析:
通常的树的遍历算法都是先遍历访问左子树,再访问右子树,我们设计一种新的遍历算法,先访问右子树,再访问左子树。并且我们需要考虑到空结点。

struct TreeNode{    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode( int x ) :        val( x ), left( NULL ), right( NULL ) {}};class Solution{public:    vector<vector<int> > printBinaryTreeEveryLayer( TreeNode* pRoot )    {        if ( pRoot == NULL )            return vector<vector<int> >();        int nextCount = 0;        int leftCount = 1;        int i = 0;          //控制行数        queue<TreeNode*> touchNode;        vector<vector<int> > result;        vector<int> temp;        touchNode.push( pRoot );        while ( !touchNode.empty() )        {            temp.push_back( touchNode.front()->val );            if ( touchNode.front()->left != NULL )            {                touchNode.push( touchNode.front()->left );                nextCount++;            }            if ( touchNode.front()->right != NULL )            {                touchNode.push( touchNode.front()->right );                nextCount++;            }            touchNode.pop();            if ( --leftCount == 0 )            {                leftCount = nextCount;                nextCount = 0;                result.push_back( temp );                temp.clear();            }        }        return result;    }};