leetCode(15):Symmetric Tree 分类: leetCode 2015-06-21 11:49 78人阅读 评论(0) 收藏

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.

首先递归方法:

bool isChildSymmectric(TreeNode* node1,TreeNode* node2)
{
	if(node1==NULL && node2==NULL)
		return true;
	if(node1==NULL || node2==NULL || node1->val!=node2->val)
		return false;
	return isChildSymmectric(node1->left,node2->right) && isChildSymmectric(node1->right,node2->left);
}

bool isSymmetric(TreeNode* root)
{
	if(root==NULL)
		return true;	
	return isChildSymmectric(root->left,root->right);
}

循环方法:把左右子树依次压入到容器中,并一层一层地判断,如果不平衡则立即返回;直至没有新的结点压入到容器中。

/**
 * 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:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)
    		return true;
    	vector<TreeNode*> nodes;
    	nodes.push_back(root);
    	int nodesBegin=0;
    	int nodesEnd=nodes.size();	
    	
    	while(nodesBegin<nodesEnd)
    	{
    		int b=nodesBegin;
    		int e=nodes.size()-1;
    		while(b<e)
    		{
    			if(nodes[b]==NULL && nodes[e]==NULL)
    			{
    				b++;
    				e--;
    				continue;
    			}
    			if((nodes[b]==NULL && nodes[e]) || (nodes[b] && nodes[e]==NULL)
    				|| (nodes[b]->val!=nodes[e]->val))
    				return false;
    				
    			nodes.push_back(nodes[b]->left);
    			nodes.push_back(nodes[b]->right);
    			
    			b++;
    			e--;			
    		}
    		while(b<nodesEnd)
    		{
    			if(NULL==nodes[b])
    			{
    				b++;
    				continue;
    			}
    			nodes.push_back(nodes[b]->left);
    			nodes.push_back(nodes[b]->right);
    			b++;
    		}
    		nodesBegin=nodesEnd;
    		nodesEnd=nodes.size();
    	}
    	return true;
    }
};


posted @ 2015-06-21 11:49  朱传林  阅读(149)  评论(0编辑  收藏  举报