码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode(15):Symmetric Tree

时间:2015-06-21 14:37:26      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:leetcode   symmetric   

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;
    }
};


leetCode(15):Symmetric Tree

标签:leetcode   symmetric   

原文地址:http://blog.csdn.net/walker19900515/article/details/46581207

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!